From another answer on Stackoverflow is a conversion from Javascript date to .net DateTime:
long msSinceEpoch = 1260402952906; // Value from Date.getTime() i
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));
}
Good luck
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.
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")');
<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);
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);
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.