Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change DateTimeOffset.Offset Property?

My end goal is to get universal time from client with NO offset - just UTC time. I try to accomplish this like so:

Javascript: (new Date()).toUTCString(), the output of which logs: Thu, 17 Mar 2016 15:13:23 GMT, which is exactly what I need.

Then I take it to server and try to convert it to DateTimeOffset:

string dateTimeOffsetPattern = "ddd, dd MMM yyyy HH:mm:ss 'GMT'"; 

DateTimeOffset clientLoginTime = DateTimeOffset.ParseExact
    (timeStringFromClient, dateTimeOffsetPattern, CultureInfo.InvariantCulture);

Which results in:

3/17/2016 3:13:23 PM -04:00 

Somehow it adjusts the time for my local (Eastern) offset. I do NOT want this to happen, I want it to just return the UTC time, like so:

3/17/2016 3:13:23 PM +00:00

P.S. I did just ask another question about this, and I apologize, since I feel like it should be easy enough, but I don't get it. This should be really simple, but it looks like offset doesn't have a setter (unless I am completely missing some C# basics as usual):

public TimeSpan Offset { get; }
like image 933
VSO Avatar asked Jul 18 '26 19:07

VSO


2 Answers

There's an overload of ParseExact where you can specify a DateTimeStyles. One of the values of DateTimeValues is AssumeUniversal, which says:

If format does not require that input contain an offset value, the returned DateTimeOffset object is given the UTC offset (+00:00).

which basically means "don't assume it's local, assume it's universal." Assuming local is the default, which is why you're seeing the result you are in that it's adjusting to local. Specifying AssumeUniversal should parse it the way you want.

DateTimeOffset clientLoginTime = DateTimeOffset.ParseExact
(timeStringFromClient, dateTimeOffsetPattern, CultureInfo.InvariantCulture, 
    DateTimeStyles.AssumeUniversal);
like image 151
Dave Zych Avatar answered Jul 20 '26 09:07

Dave Zych


I would parse from JS normally, then do the following:

  • Strip OffSet from DateTimeOffset by returning DateTime
  • Set OffSetby instantiating another DateTimeOffset having TimeSpan set to ZERO.

In your case:

var clientLoginTime = new DateTimeOffset(clientLoginTime.DateTime, TimeSpan.FromHours(0));

This can be easily converted into an extension method

public static DateTimeOffset SetOffset(this DateTimeOffset dto, int timeZoneDiff)
{
    return new DateTimeOffset(dto.DateTime, TimeSpan.FromHours(timeZoneDiff));
}
like image 40
Korayem Avatar answered Jul 20 '26 08:07

Korayem