Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Datetime datatype between javascript and WebApi 2

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
like image 952
Shyamal Parikh Avatar asked Oct 26 '15 07:10

Shyamal Parikh


1 Answers

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

like image 171
Anestis Kivranoglou Avatar answered Nov 03 '22 08:11

Anestis Kivranoglou