I wish to return a Json Result containing the datetime queried from database. The testing on my local machine is without any problem, however, after publishing to production server, all datetime show 3 hours ahead. I assume it is due to the server located in another timezone area.
Need help to solve this issue.
Data in Database (MS SQL):
StartDt: 2019-07-02 04:00:00.000
Controller.cs:
[HttpGet]
public ActionResult GetAll()
{
CalendarModel calendarModel = new CalendarModel();
var calendarEvents = from cal in db.Calendar
orderby cal.created descending
select cal;
return Json(calendarEvents, JsonRequestBehavior.AllowGet);
}
Json Result Fetched from my compuer:
[
{
//some data
"startDt": "/Date(1562054400000)/",
//some data
},
The above datetime is parsed as "2019-07-02T04:00:00.000-04:00", which is correct.
Json Result Fetched from production server (queried from same database):
[
{
//some data
"startDt": "/Date(1562065200000)/",
//some data
},
This datetime is "2019-07-02T07:00:00.000-04:00", which is wrong.
--------Update my solution-------
Thank @TommasoBertoni's answer inspired me that the key reason for this issue is due to the Unspecified DateTime Kind by default but turns to be local while Json serializing. So just need to set the DateTime Kind to UTC can solve that, but be aware that parsing the DateTime in front end also need to take it as UTC otherwise it will be considered as local by default.
Controller.cs:
[HttpGet]
public ActionResult GetAll()
{
CalendarModel calendarModel = new CalendarModel();
var calendarEvents = from cal in db.Calendar
orderby cal.created descending
select cal;
//Add this
foreach (var item in calendarEvents)
{
item.startDt = DateTime.SpecifyKind(item.startDt, DateTimeKind.Utc);
}
return Json(calendarEvents, JsonRequestBehavior.AllowGet);
}
.js
(using moment.js library)
//parse it as utc
moment.utc(startDt).format("YYYY-MM-DDTHH:mm:ss")
Dateinto a date object and where are you getting your "date" (2019-07-02T07:00:00.000-04:00) from on the client side? That looks like a date representation for a UTC-4 timezone, so your assesment that2019-07-02T04:00:00.000-04:00"is correct" doesn't seem right