admin管理员组文章数量:1134247
From another answer on Stackoverflow is a conversion from Javascript date to 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?
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?
Share Improve this question edited Mar 26, 2018 at 11:22 MSeifert 152k41 gold badges349 silver badges366 bronze badges asked Mar 8, 2010 at 19:50 AJ.AJ. 11.2k14 gold badges43 silver badges51 bronze badges 2- 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 Commented Mar 8, 2010 at 20:04
- 2 You should link the answer you're referring to – cdmckay Commented May 23, 2014 at 23:17
12 Answers
Reset to default 134Try:
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.
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);
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")');
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
This should do the trick:
date.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
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
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.
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;
}
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
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);
}
You should serialize a C# DateTime value to a string before using that string in your JavaScript code if you want to pass a C# DateTime value to JavaScript. Here is how to go about it:
@{
ViewData["Title"] = "Home Page";
var minDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 5, 10, 0, 0);
var minDateStr = minDate.ToString("yyyy-MM-ddTHH:mm:ss"); // Serialize DateTime to a string
}
<script>
// Define an onload function
function onPageLoad() {
console.log("Page is loaded!");
var tempDate = new Date("@minDateStr"); // Parse the serialized DateTime string to a JavaScript Date object
console.log("minDate:", tempDate);
}
// Add the onload function to the window's onload event
window.onload = onPageLoad;
</script>
<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);
本文标签: cDateTime to javascript dateStack Overflow
版权声明:本文标题:c# - DateTime to javascript date - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736781957a1952648.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论