Ans
Ans

Reputation: 344

What is the best way to send Date from client(Javascript) to WebApi

I need to send only Date without time to Web Api to get data w.r.t to date send. There are two ways to send it.

  1. Convert it to Date.ISOString and receive as DateTime object in webapi. (but when you convert it to ISOString it removes offset hoours w.r.t UTC) and when webApi receives this datetime object takes it into local timezone). Since the date stored in database is in UTC format,I again need to convert it to UTC format for comparison.

  2. Send datetime as string to web api in isoformat and then convert it to Datetime in utc format. I am feeling 2nd option is more reliable.

Is there any good alternative.

Upvotes: 4

Views: 10238

Answers (3)

Arwin
Arwin

Reputation: 1023

DateTime in .NET has DateTimeKind UTC, Local and Unspecified. This last one is very useful, especially if you only want to use the day and don't want the day to change because of an accidental conversion (but there are many other reasons to use this as well).

If you just pass the datetime without TimeOffset or UTC markers, typically your json will be converted to DateTime Unspecified. If you pass it with a z (UTC) or a + (timezone) it will use UTC or Local.

For some more thoughts on DateTime, see also a blog I wrote: https://www.linkedin.com/pulse/i-datetimeprovider-arwin-van-arum?trk=prof-post

Upvotes: 0

Luca Ghersi
Luca Ghersi

Reputation: 3321

You need to use DateTimeOffset object instead of DateTime object on the server side (check this SO answer for more details). On the client side, use moment.js too like this: moment.utc().format().

Using DateTimeOffset you will keep all the timezone information without losing anything.

Hope it helps :)

Upvotes: 0

jwoo
jwoo

Reputation: 167

When dealing with dates and times I like to use moment.js

It's a cool javascript library that helps you parse, validate, manipulate, and display dates.

Example:

moment().format('MMMM Do YYYY, h:mm:ss a');
moment().subtract(10, 'days').calendar(); 
moment().subtract(6, 'days').calendar();
moment("20111031", "YYYYMMDD").fromNow(); 

You can use utc formats:

moment().format();     // 2013-02-04T10:35:24-08:00
moment.utc().format(); // 2013-02-04T18:35:24+00:00

Upvotes: 2

Related Questions