If you are dealing with dates in your code and need to convert values between different systems, such as passing dates back and forth in JavaScript, there are specific methods to handle this.
var d = new Date()
d.setTime(-62135575200000);
alert(d.toDateString());
You can refer to the discussion on Converting .NET DateTime to JSON for further insights and solutions provided by the community.
Below are two approaches mentioned for moving dates within the code:
[WebMethod]
public static DateTime loadDate()
{
return DateTime.Now;
}
[WebMethod]
public static double loadDateTicks()
{
return DateTime.Now.UnixTicks();
}
public static class ExtensionMethods
{
// Calculate the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
}
Credit is given to "Jeff Meatball Yang" for providing the extension method mentioned above.
For testing purposes, here is a sample frontend function:
function LoadDates() {
$.ajax({
url: "Default.aspx/loadDate",
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
var re = /-?\d+/;
var d = new Date(parseInt(re.exec(msg.d)[0]));
alert(d.toDateString());
},
dataType: "json"
});
$.ajax({
url: "Default.aspx/loadDateTicks",
type: "POST",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (msg) {
var dt = new Date(msg.d);
alert(dt.toDateString());
},
dataType: "json"
});
}