Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript date to C# via Ajax

I have javascript date object which gives me a date string in this format, "Wed Dec 16 00:00:00 UTC-0400 2009".

I pass this via Ajax to the server (ASP.NET c#)

How can I convert, "Wed Dec 16 00:00:00 UTC-0400 2009" to a C# DateTime object. DateTime.Parse fails.

like image 777
Ian Vink Avatar asked Dec 09 '09 23:12

Ian Vink


People also ask

How to convert JavaScript Date to c# DateTime?

Use the DateTime. ParseExact() in codebehind to convert this string to DateTime as follows, DateTime. ParseExact(YourString, "dd/MM/yyyy HH:mm:ss", CultureInfo.

How do I format a date in JavaScript?

const d = new Date("2015/03/25"); The behavior of "DD-MM-YYYY" is also undefined. Some browsers will try to guess the format. Some will return NaN.

What is new Date () in JavaScript?

It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.

What does new Date () return?

"The expression new Date() returns the current time in internal format, as an object containing the number of milliseconds elapsed since the start of 1970 in UTC.


2 Answers

You can use DateTime.ParseExact which allows you to specify a format string to be used for parsing:

DateTime dt = DateTime.ParseExact("Wed Dec 16 00:00:00 UTC-0400 2009",                                   "ddd MMM d HH:mm:ss UTCzzzzz yyyy",                                   CultureInfo.InvariantCulture); 
like image 101
dtb Avatar answered Oct 10 '22 08:10

dtb


The most reliable way would be to use milliseconds since the epoch. You can easily get this in JavaScript by calling Date.getTime(). Then, in C# you can convert it to a DateTime like this:

long msSinceEpoch = 1260402952906; // Value from Date.getTime() in JavaScript return new DateTime(1970, 1, 1).AddTicks(msSinceEpoch * 10000); 

You have to multiply by 10,000 to convert from milliseconds to "ticks", which are 100 nanoseconds.

like image 41
EMP Avatar answered Oct 10 '22 09:10

EMP