Reputation: 227
This is how I convert .Net Datetime to Javascript. I found the code somewhere a long time ago and use it for Highcharts. Now the chart sometimes looks strange with the lines messed up. I suspect it has to do with the date.
Datetime curDate = "11/14/2013";
string jsDate = "Date.UTC(" + curDate.Year + "," + (curDate.Month - 1) + "," + curDate.Day;
if (curDate.Millisecond > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second + "," + curDate.Millisecond;
return jsDate += ")";
}
if (curDate.Second > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute + "," + curDate.Second;
return jsDate += ")";
}
if (curDate.Minute > 0)
{
jsDate += "," + curDate.Hour + "," + curDate.Minute;
return jsDate += ")";
}
if (curDate.Hour > 0)
{
jsDate += "," + curDate.Hour;
return jsDate += ")";
}
jsDate += ")";
Is this a correct way to convert .Net date to javascript?
Thank you!
Upvotes: 0
Views: 1502
Reputation: 245429
The easiest way to convert between the two is to convert the .NET time to a timespan in milliseconds from the UNIX epoch time:
public static long ToEpochDate(this DateTime dt)
{
var epoch = new DateTime(1970, 1, 1);
return dt.Subtract(epoch).Ticks;
}
You can then use that to generate your JS string:
DateTime current = DateTime.Now;
var jsDate = string.Format("Date.UTC({0})", current.ToEpochDate());
Upvotes: 3