Formatting DateTime to string with timezone information for Date created in Javascript

℡╲_俬逩灬. 提交于 2020-01-06 21:08:30

问题


In this massively oversimplified example, I have a controller method that accepts a DateTime

[Route("api/demo)]
public IHttpActionResult Post(DateTime date)
{
   // format dateTime here
}

We call this from the client with Javascript.

var data = {
    date: new Date()
};

$.ajax({
    url: "/api/demo",
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify(data),
});

The new Date() part is what I feel is the important part, as we're trying to record the date as the calling client sees it (their local time)

What is the best way to format the DateTime object as a string, so that it records the timezone information, and can be parsed back into a DateTime object again later if required?

(We're storing this formatted string in an analytics recording platform / data warehouse)


回答1:


You don't need to perform any conversions, just change the parameter type to DateTimeOffset:

[Route("api/demo)]
public IHttpActionResult Post(DateTimeOffset date)
{
    //use the date without conversions.
}

JSON.stringify serializes the date using the ISO8601 format (eg "2017-01-10T14:52:04.780Z") which can be parsed directly to a DateTimeOffset. DateTimeOffset allows you to compare values with different offsets directly, removing the need to convert to the same timezone

By using DateTimeOffset you avoid the confusion between local and UTC DateTime values. Without knowing the timezone offset you don't really know what "local" refers to - the client's or the server's timezone?




回答2:


You can use new Date().getTimezoneOffset() in javascript to know the difference between the current time zone of the client and the UTC. It offset will be in minute. Example - TimezoneOffset between Singapore Time and UTC is -480 minutes.

http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp

Then create a cookie in the javascript and store that offset in it.

function setTimezoneCookie(){

    var timezone_cookie = "timezoneoffset";

    if (!$.cookie(timezone_cookie)) { 
        // create a new cookie 
        $.cookie(timezone_cookie, new Date().getTimezoneOffset());
    }
}

Every request goes to the server will carry that cookie and at server side convert the dateTime submitted by client to UTC by Adding the offset from cookie and save it in the database. This would ensure that no matter in what timezone user is the data will always have UTC date and time uniformly.

Also when displaying the datetime information in the UI, convert it to the client time by substracting offset retrieved from cookie before sending to the UI.

This way it will be sure that user sees the dates and time as per it's client machines timezone.

Extension methods would be handy in this case.

public static DateTime ToClientTime(this DateTime dt)
    {
        // read the value from session
        var timeOffSet = HttpContext.Current.Request["timezoneoffset"];

        if (timeOffSet != null)
        {
            var offset = int.Parse(timeOffSet.ToString());
            dt = dt.AddMinutes(-1 * offset);

            return dt;
        }

        // if there is no offset in session return the datetime as it is
        return dt;
    }

public static DateTime ToUtcTime(this DateTime dt)
    {
        // read the value from session
        var timeOffSet = HttpContext.Current.Request["timezoneoffset"];

        if (timeOffSet != null)
        {
            var offset = int.Parse(timeOffSet.ToString());
            dt = dt.AddMinutes(offset);

            return dt;
        }

        // if there is no offset in session return the datetime as it is

        return dt;
    }

This should resolve help you resolving your issue.



来源:https://stackoverflow.com/questions/41570594/formatting-datetime-to-string-with-timezone-information-for-date-created-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!