简体   繁体   中英

get server time on the client side in javascript / jquery

I want to use, on the client side, dates as they are on the server side.
for example- if the current time on the server side is '2011-09-21 15:00:00', I want to be able to get a javascript Date object with that value ('15:00:00'), even if the client is in a different time zone.
what i've tried so far:
suppose the server time is '15:00:00' and client time is '17:00:00', The Date object I get on the client side always contains '16:00:00', for some reason.
here's what i've tried:
1. sending a .net DateTime object to the client (it gets serialized as "Date\\12345...\\" ), and on the client side converting it to a Date object:

function parseServerDate(strDate) {
    return new Date(parseInt(strDate.substr(6)));
}

OR converting the .net DateTime object into a UTC number:

    // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
    public static double UnixTicks(this DateTime dateTime)
    {
        DateTime epoch = new DateTime(1970, 1, 1);
        DateTime d2 = dateTime.ToUniversalTime();
        TimeSpan ts = new TimeSpan(d2.Ticks - epoch.Ticks);
        return ts.TotalMilliseconds;
    }

and then creating a new Date object:
new Date(milliseconds) or new Date().setTime(milliseconds) , both of which produced the same result as above.

should I maybe send the server's timezone offset as well, and handle the difference in the client side?
What's the best way to go about it?

If it's about display, why do you need a Date object client-side? Why not simply have the server send the datetime as string and let the client display it as is?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM