17

I have a date in JavaScript and its value is coming like this

Fri Apr 01 2011 05:00:00 GMT+0530 (India Standard Time) {}

Now what is the best way to convert the date to .NET date . Note that my client side users can be anwyehere around the world. I will have the date from there now my need is to convert it to the .NET date. can you help me ?

NotMe
  • 87,343
  • 27
  • 171
  • 245
Rocky Singh
  • 15,128
  • 29
  • 99
  • 146

5 Answers5

26

Possible duplicate of the question answered here: Javascript date to C# via Ajax

If you want local time, like you are showing in your question the following would do it.

DateTime.ParseExact(dateString.Substring(0,24),
                              "ddd MMM d yyyy HH:mm:ss",
                              CultureInfo.InvariantCulture);

If you are looking for GMT time, doing a dateObject.toUTCString() in Javascript in the browser before you send it to the server, would do it.

Community
  • 1
  • 1
Naraen
  • 3,240
  • 2
  • 22
  • 20
14

Convert JavaScript into UTCString from Client side:

var testDate = new Date().toUTCString();

Parse it from C# code (you can fetch js date through webservice call).

DateTime date = DateTime.Parse(testDate);
Gaʀʀʏ
  • 4,372
  • 3
  • 39
  • 59
SumairIrshad
  • 1,641
  • 1
  • 13
  • 11
0

Expanding on @Naraen's answer, my javascript date was in the following format:

Thu Jun 01 2017 04:00:00 GMT-0400 (Eastern Standard Time)

Which required two lower case d's for the day (dd) for the conversion to work for me in C#. See update to @Naraen's code:

DateTime.ParseExact(dateString.Substring(0,24),
                          "ddd MMM dd yyyy HH:mm:ss",
                          CultureInfo.InvariantCulture);
Daniel Congrove
  • 3,519
  • 2
  • 35
  • 59
0

You can convert your time to string before you send it and in the .net you should convert a string into datetime using one of datetime constructor. Datetime .net -> http://msdn.microsoft.com/en-us/library/system.datetime(v=VS.90).aspx You can use also a DateTime.Parse method -> http://msdn.microsoft.com/en-us/library/ms973825.aspx But you should deliver a correct form of string to server

nosbor
  • 2,826
  • 3
  • 39
  • 63
0

Ok here try this simple function which will convert your `double' representation of your Unix Timestamp

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0);
    return origin.AddMilliseconds(timestamp); 
}
Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79