112

From another answer on Stackoverflow is a conversion from Javascript date to .net DateTime:

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

But how to do the reverse? DateTime to Javascript Date?

MSeifert
  • 145,886
  • 38
  • 333
  • 352
AJ.
  • 10,732
  • 13
  • 41
  • 50
  • In questions like this that are obviously ajax related, you should specify where you are doing the conversion, and considering that there is no standard for date serialization in JSON and that it is possible that you are dealing with MS Date munging e.g. /Date(02020202)/ be sure to make that clear as well. good luck – Sky Sanders Mar 08 '10 at 20:04
  • 2
    You should link the answer you're referring to – cdmckay May 23 '14 at 23:17

11 Answers11

130

Try:

return DateTime.Now.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds

Edit: true UTC is better, but then we need to be consistent

return DateTime.UtcNow
               .Subtract(new DateTime(1970,1,1,0,0,0,DateTimeKind.Utc))
               .TotalMilliseconds;

Although, on second thoughts it does not matter, as long as both dates are in the same time zone.

AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
  • 5
    You might want to use DateTime.UtcNow instead of DateTime.Now – Matt Dearing Mar 08 '10 at 19:57
  • 2
    Regarding your second thoughts: it does matter during the transition to or from daylight saving time (I always have to think really hard to remember which :). During the transition the hour of 2:00 to 3:00 is repeated twice. This means that during one hour the javascript date will be off by one hour. UTC does not have DLS so it does not have that problem. – Sebastiaan M Jan 09 '16 at 19:05
  • I have same code here but it makes 5:30 difference in javascript date while C# date works fine. – Jenish Zinzuvadiya Sep 24 '16 at 13:08
50

JavaScript Date constructor accepts number of milliseconds since Unix epoch (1 January 1970 00:00:00 UTC). Here’s C# extension method that converts .Net DateTime object to JavaScript date:

public static class DateTimeJavaScript
{
   private static readonly long DatetimeMinTimeTicks =
      (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).Ticks;

   public static long ToJavaScriptMilliseconds(this DateTime dt)
   {
      return (long)((dt.ToUniversalTime().Ticks - DatetimeMinTimeTicks) / 10000);
   }
}

JavaScript Usage:

var dt = new Date(<%= DateTime.Today.ToJavaScriptMilliseconds() %>);
alert(dt);
Yair Nevet
  • 12,725
  • 14
  • 66
  • 108
  • C# usage long date = DateTimeJavaScript.ToJavaScriptMilliseconds(DateTime); check in javascript (Press F12 in Google Chrome and go to console) var date = new Date(long); console.log(date.toString()); – Gonen09 Feb 03 '20 at 15:11
36

You can try this in your Action:

return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");

And this in your Ajax success:

success: function (resultDateString) {
    var date = new Date(resultDateString);
}

Or this in your View: (Javascript plus C#)

var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
Renan Cerqueira
  • 499
  • 4
  • 8
27

With Moment.js simply use:

var jsDate = moment(netDateTime).toDate();

Where netDateTime is your DateTime variable serialized, something like "/Date(1456956000000+0200)/".

Marco Lackovic
  • 6,077
  • 7
  • 55
  • 56
  • Why not just JavaScript constructor `new Date(netDateTime)`? – Kamil Oct 19 '20 at 20:42
  • 2
    @Kamil momentjs [can parse ASP.NET json data](https://momentjs.com/docs/#/parsing/asp-net-json-date/), vanilla js can't – Oleg Jul 19 '21 at 01:25
13

This should do the trick:

date.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Community
  • 1
  • 1
munissor
  • 3,755
  • 22
  • 24
6

Another late answer, but this is missing here. If you want to handle conversion of serialized /Date(1425408717000)/ in javascript, you can simply call:

var cSharpDate = "/Date(1425408717000)/"
var jsDate = new Date(parseInt(cSharpDate.replace(/[^0-9 +]/g, '')));

Source: amirsahib

Kajbo
  • 1,068
  • 3
  • 16
  • 31
  • 1
    It's an answer but, Yuck. I don't recommend it. Two hacks don't make a right. And Microsoft's serialization is a distasteful hack. – Suncat2000 Feb 27 '19 at 17:55
  • 1
    @Suncat2000 how is this hack? If you are using a service for retrieving value from server to front-end, I do not know any better alternative. This is the cleanest solution of the problem on this page. If you know of better alternative, care to show us example? – Kajbo Feb 28 '19 at 09:09
4

I know this is a little late, but here's the solution I had to come up with for handling dates when you want to be timezone independent. Essentially it involves converting everything to UTC.

From Javascript to Server:

Send out dates as epoch values with the timezone offset removed.

var d = new Date(2015,0,1) // Jan 1, 2015
// Ajax Request to server ...
$.ajax({
  url: '/target',
  params: { date: d.getTime() - (d.getTimezoneOffset() * 60 * 1000) }
});

The server then recieves 1420070400000 as the date epoch.

On the Server side, convert that epoch value to a datetime object:

DateTime d = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(epoch);

At this point the date is just the date/time provided by the user as they provided it. Effectively it is UTC.

Going the other way:

When the server pulls data from the database, presumably in UTC, get the difference as an epoch (making sure that both date objects are either local or UTC):

long ms = (long)utcDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;

or

long ms = (long)localDate.Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local)).TotalMilliseconds;

When javascript receives this value, create a new date object. However, this date object is going to be assumed local time, so you need to offset it by the current timezone:

var epochValue = 1420070400000 // value pulled from server.
var utcDateVal = new Date(epochValue);
var actualDate = new Date(utcDateVal.getTime() + (utcDateVal.getTimezoneOffset() * 60 * 1000))

console.log(utcDateVal); // Wed Dec 31 2014 19:00:00 GMT-0500 (Eastern Standard Time)
console.log(actualDate); // Thu Jan 01 2015 00:00:00 GMT-0500 (Eastern Standard Time)

As far as I know, this should work for any time zone where you need to display dates that are timezone independent.

Code Monkey
  • 121
  • 1
  • 9
3

This method is working for me:

   public sCdateToJsDate(cSDate: any): Date {
        // cSDate is '2017-01-24T14:14:55.807'
        var datestr = cSDate.toString();
        var dateAr = datestr.split('-');
        var year = parseInt(dateAr[0]);
        var month = parseInt(dateAr[1])-1;
        var day = parseInt(dateAr[2].substring(0, dateAr[2].indexOf("T")));
        var timestring = dateAr[2].substring(dateAr[2].indexOf("T") + 1);
        var timeAr = timestring.split(":");
        var hour = parseInt(timeAr[0]);
        var min = parseInt(timeAr[1]);
        var sek = parseInt(timeAr[2]);
        var date = new Date(year, month, day, hour, min, sek, 0);
        return date;
    }
alexey
  • 783
  • 1
  • 7
  • 19
1

If you use MVC with razor

-----Razor/C#

var dt1 = DateTime.Now.AddDays(14).Date;
    var dt2 = DateTime.Now.AddDays(18).Date;

    var lstDateTime = new List<DateTime>();
    lstDateTime.Add(dt1);
    lstDateTime.Add(dt2);

---Javascript

$(function() {

            var arr = []; //javascript array

            @foreach (var item in lstDateTime)
             {
                @:arr1.push(new Date(@item.Year, @(item.Month - 1), @item.Day));
             }
  • 1: create the list in C# and fill it
  • 2: Create an array in javascript
  • 3: Use razor to iterate the list
  • 4: Use @: to switch back to js and @ to switch to C#
  • 5: The -1 in the month to correct the month number in js.

Good luck

Dinand
  • 330
  • 2
  • 17
0

I did this using date time format.

C# to JS

public static class DateTimeExtension
{
    public static string ToJsString(this DateTime @this)
    {
        return @this.ToString("ddd, dd MMM yyyy HH:mm:ss") + " GMT";
    }
}

JS to C#

 public  DateTime ParseJSDate(this string jsDate)
 {
     return DateTime.ParseExact(jsDate, "ddd, dd MMM yyyy HH:mm:ss GMT", CultureInfo.InvariantCulture);
 }
Sandeep Kumar
  • 1,505
  • 1
  • 15
  • 24
-1
<input type="hidden" id="CDate" value="<%=DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")%>" />

In order to convert the date to JS date(all numbers):

var JSDate = $("#CDate").val();
JSDate = Date.parse(JSDate);
syaakobi
  • 1
  • 1