Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default ASP.NET DateTime.Kind to UTC in Web Method

Tags:

c#

asp.net

I'm passing the following ISO 8601 date string to an ASP.NET Web Method:

2013-04-01T00:00:00.000Z

This is automatically creating a date object with the following properties:

Value: 3/31/2013 8:00:00 PM
Kind:  Local (EDT)

This is annoying because I now have to remember to convert all my date objects to UTC by doing the following:

date = date.ToUniversalTime();

How can I change asp.net to make dates passed into a Web Method be in UTC by default instead of the server's local time? Is there some configuration or hook that I can use to achieve this? Or maybe this just isn't possible?

I don't want to have to bother dealing with server's local time at all because it's completely irrelevant.


Edit

Just adding a bit more information because I seem to have not explained myself that clearly above. Here is some example code.

JavaScript:

PageMethods.SendData("2013-04-01T00:00:00.000Z");

C#:

[WebMethod]
static public void SendData(DateTime date)
{
    // The value of date in here is 3/31/2013 8:00:00 PM Local
    // How can I make it so the default is 04/01/2014 0:00:00 AM Utc
    // without typing any extra code in here? 
    // How can I change ASP.NET's default behaviour?
    // I don't want to rely on the developer remembering.
}
like image 618
David Sherret Avatar asked Oct 21 '22 08:10

David Sherret


2 Answers

I found a workaround, but I'll still accept an answer that shows how to change the default behaviour of asp.net to default to the UTC date instead of the server's local time in the Web Method.

It seems that the value in the Date object will default to local time when the time zone is specified.

The trick is to not pass in the time zone. So any of these strings will work:

2013-04-01T00:00:00.000 // leave off the Z at the end of the ISO 8601 string

2013-04-01 00:00:00

2013-04-01

This, however, makes a date object with the following properties in the Web Method:

Value: 4/01/2013 0:00:00 AM

Kind: Unspecified

The kind is unspecified, but the date objects properties remain in UTC, which is what matters for my purposes.

like image 113
David Sherret Avatar answered Oct 23 '22 04:10

David Sherret


See DateTimeOffset The browser may be in a different Timezone. If you are sure this is correct then you should remember that the LocalTimeZone is used by default when sending dates to the server and thus conversion would change the time. You may have to use the SpecifyKind method.

I do believe if you specify the Timezone in the string you can get ASP.Net to pick it up also...

If not use a new parser and register it as the default or create a new type with the offset.

like image 26
Jay Avatar answered Oct 23 '22 03:10

Jay