Search code examples
c#javascriptdatetimedatetime-conversion

Convert javascript gettime() to c# datetime


I use telerik raddatepicker control to select a date.

I get the date value from the control, convert it into javascript Date object and then use getTime to get the total milliseconds:

            var FromDate = $find("<%=fromDate.ClientID%>").get_dateInput().get_displayValue();
            var FromDateMill = new Date(FromDate).getTime();

The date I choose is 6/4/2012 (us). when I print the result of new Date(FromDate) I get the correct date I chose.

In server side, I try to get datetime object using the milliseconds I got from the javascript so I use this code:

DateTime seventies = new DateTime(1970, 1, 1);
DateTime fromDate = seventies.AddMilliseconds(Convert.ToDouble(Reader["FromDateMill"]));

but when I print fromDate I get 6/3/2012 9:00:00 AM (a day before..). I checked and saw that the conversion toDouble returns the correct number of milliseconds as I got in the javascript.

Does anyone has an idea what am I doing wrong?

Thanks, Inbal.


Solution

  • The value that you get from the getTime method is not from the local time, but from the universal time. When you add those milliseconds to 1970-1-1, you get the universal time, not the local time.

    Use the ToLocal method to get the DateTime value for the local time:

    DateTime fromDate =
      seventies.AddMilliseconds(Convert.ToDouble(Reader["FromDateMill"])).ToLocal();