Handling Datetime datatype between javascript and WebApi 2

15,923

Yes if you don't want to handle any information about user Timezone etc... this is an acceptable way. Just make sure that any time you want a date produced from the server for a comparison or something else to use the c# DateTime.UtcNow method. I think Having a "Global UTC Convention" its a quite safe and good solution but it has some limits.

For example if you want to Alert all of your users located in different timezones at 09:00 am (on each user's country) then its impossible to know when its "09:00" for each one.

One way to solve this(and it's the one i prefer), is to store manually each user's timezone info separately on the database, and every time you want to make a comparison simply convert the time.

TimeZoneInfo.ConvertTimeFromUtc(time, this.userTimezone);

Alternatively if you want to store all timezone information on the server you can :

Send your date from javascript to the server using the following format : "2014-02-01T09:28:56.321-10:00" ISO 8601 also supports time zones by replacing the Z with + or – value for the timezone offset.

Declare your WEB API 2 Date types with the "DateTimeOffset" type.

Finally store your dates within the database using the "datetimeoffset" type.

This way any time on the server or the database you have all the information about the user's time and timezone.

You will find this article useful

Share:
15,923
Shyamal Parikh
Author by

Shyamal Parikh

Updated on July 20, 2022

Comments

  • Shyamal Parikh
    Shyamal Parikh almost 2 years

    I would like to know whether the following is the right method to handle datetime data type in WebApi 2, Javascript and database.

    DateTime from Javascript to WebApi:

    var date = new Date();
    var datestring = date.toISOString();
    //Send datestring to WebApi
    

    DateTime from WebApi to Javascript:

    //on getting datetime value from `http.get` call 
    var dateFromServer = new Date(dateFromServer); 
    

    WebApi:

    Incoming date

    • do nothing simply store the datestring returned in database column with datatype datetime

    Getting date from database and Returning date to client:

    • no datetime manipulation (simply return as per WebApi Json serializer ex: 2015-10-23T18:30:00). Client would automatically convert the UTC datetime to local datetime