Datetime data type processing between javascript and WebApi 2

I would like to know if a suitable method for processing 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:

receipt date

  • do nothing, just save the datestring returned in the database column with datetime data type

Retrieving dates from the database and return date to the client:

  • no time handling (just go back according to the WebApi Json ex serializer: 2015-10-23T18: 30: 00). Client automatically converts UTC date and time to local datetime
+8
javascript c # datetime asp.net-web-api
source share
1 answer

Yes, if you do not want to process any information about the user's time zone, etc .... this is an acceptable way. Just make sure that anytime you want to get the date received from the server, for comparison or something else, to use the C # DateTime.UtcNow method. I think that having the UTC Global Convention is a safe and good solution, but it has some limitations.

For example, if you want to notify all your users who are in different time zones at 09:00 (in each country of the user), then it is impossible to find out when their "09:00" for each of them.

One way to solve this problem (and this is the one that I prefer) is to manually save each time zone information of each user in the database, and every time you want to make a comparison, just convert the time.

 TimeZoneInfo.ConvertTimeFromUtc(time, this.userTimezone); 

Alternatively, if you want to save all the time zone 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, replacing Z with + or - the time zone offset value.

Declare the WEB API 2 data type types with the DateTimeOffset type.

Finally, save your dates in the database using the "datetimeoffset" type .

Thus, at any time on the server or in the database you have all the information about the time and time zone of the user.

You will find this article helpful.

+8
source share

All Articles