Rectangle 27 13

I have a suspicion, that the Answer doesn't give the correct result. In the question the asker wants to convert timestamp from server to current time in Hellsinki disregarding current time zone of the user.

It's the fact that the user's timezone can be what ever so we cannot trust to it.

If eg. timestamp is 1270544790922 and we have a function:

var _date = new Date();
_date.setTime(1270544790922);
var _helsenkiOffset = 2*60*60;//maybe 3
var _userOffset = _date.getTimezoneOffset()*60*60; 
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);

When a New Yorker visits the page, alert(_helsenkiTime) prints:

Tue Apr 06 2010 05:21:02 GMT-0400 (EDT)

And when a Finlander visits the page, alert(_helsenkiTime) prints:

Tue Apr 06 2010 11:55:50 GMT+0300 (EEST)

So the function is correct only if the page visitor has the target timezone (Europe/Helsinki) in his computer, but fails in nearly every other part of the world. And because the server timestamp is usually UNIX timestamp, which is by definition in UTC, the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), we cannot determine DST or non-DST from timestamp.

So the solution is to DISREGARD the current time zone of the user and implement some way to calculate UTC offset whether the date is in DST or not. Javascript has not native method to determine DST transition history of other timezone than the current timezone of user. We can achieve this most simply using server side script, because we have easy access to server's timezone database with the whole transition history of all timezones.

But if you have no access to the server's (or any other server's) timezone database AND the timestamp is in UTC, you can get the similar functionality by hard coding the DST rules in Javascript.

To cover dates in years 1998 - 2099 in Europe/Helsinki you can use the following function (jsfiddled):

function timestampToHellsinki(server_timestamp) {
    function pad(num) {
        num = num.toString();
        if (num.length == 1) return "0" + num;
        return num;
    }

    var _date = new Date();
    _date.setTime(server_timestamp);

    var _year = _date.getUTCFullYear();

    // Return false, if DST rules have been different than nowadays:
    if (_year<=1998 && _year>2099) return false;

    // Calculate DST start day, it is the last sunday of March
    var start_day = (31 - ((((5 * _year) / 4) + 4) % 7));
    var SUMMER_start = new Date(Date.UTC(_year, 2, start_day, 1, 0, 0));

    // Calculate DST end day, it is the last sunday of October
    var end_day = (31 - ((((5 * _year) / 4) + 1) % 7))
    var SUMMER_end = new Date(Date.UTC(_year, 9, end_day, 1, 0, 0));

    // Check if the time is between SUMMER_start and SUMMER_end
    // If the time is in summer, the offset is 2 hours
    // else offset is 3 hours
    var hellsinkiOffset = 2 * 60 * 60 * 1000;
    if (_date > SUMMER_start && _date < SUMMER_end) hellsinkiOffset = 
    3 * 60 * 60 * 1000;

    // Add server timestamp to midnight January 1, 1970
    // Add Hellsinki offset to that
    _date.setTime(server_timestamp + hellsinkiOffset);
    var hellsinkiTime = pad(_date.getUTCDate()) + "." + 
    pad(_date.getUTCMonth()) + "." + _date.getUTCFullYear() + 
    " " + pad(_date.getUTCHours()) + ":" +
    pad(_date.getUTCMinutes()) + ":" + pad(_date.getUTCSeconds());

    return hellsinkiTime;
}
var server_timestamp = 1270544790922;
document.getElementById("time").innerHTML = "The timestamp " + 
server_timestamp + " is in Hellsinki " + 
timestampToHellsinki(server_timestamp);

server_timestamp = 1349841923 * 1000;
document.getElementById("time").innerHTML += "<br><br>The timestamp " + 
server_timestamp + " is in Hellsinki " + timestampToHellsinki(server_timestamp);

var now = new Date();
server_timestamp = now.getTime();
document.getElementById("time").innerHTML += "<br><br>The timestamp is now " +
server_timestamp + " and the current local time in Hellsinki is " +
timestampToHellsinki(server_timestamp);

And this print the following regardless of user timezone:

The timestamp 1270544790922 is in Hellsinki 06.03.2010 12:06:30

The timestamp 1349841923000 is in Hellsinki 10.09.2012 07:05:23

The timestamp is now 1349853751034 and the current local time in Hellsinki is 10.09.2012 10:22:31

Of course if you can return timestamp in a form that the offset (DST or non-DST one) is already added to timestamp on server, you don't have to calculate it clientside and you can simplify the function a lot. BUT remember to NOT use timezoneOffset(), because then you have to deal with user timezone and this is not the wanted behaviour.

@BenMcIntyre It's a little joke. Or supposed to be such one. :)

javascript - How to ignore user's time zone and force Date() use speci...

javascript date timezone
Rectangle 27 26

You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().

Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().

Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:

momentObj.format("YYYY-MM-DD HH:mm:ss")

Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.

A couple of other little things:

Thanks Matt! Your answer was useful. As you mentioned about using America/Denver instead of MST7MDT, Is there a map available for these mappings? I am using quite a few such timezones like CET, EET, EST5EDT, CST6CDT, PST8PDT.

is it possible to convert eg: "10:20 AM" (Obtained string time from moment().format('hh:mm A')) to Date object ??

@ram - 1) if you have a moment, just use .toDate(). 2) Don't use comments to ask new questions. That's what the big "Ask Question" button is for.

javascript - Moment.js transform to date object - Stack Overflow

javascript momentjs
Rectangle 27 116

Native Support in Modern Browsers

JavaScript's Date object tracks time in UTC internally, but typically accepts input and output in the local time of the computer it's running on. It doesn't have any facilities for working with time in other time zones. You can parse and output dates that are UTC or Local, but you can't directly work with other time zones.

To be absolutely precise, the internal representation of a Date object is a single number, representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC, without regard to leap seconds. There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.

Fortunately, there are libraries that can accomplish this. They implement the standard Olson/IANA timezone database in JavaScript. This has some overhead if you are running in a web browser, as the database can get a bit large if you want the whole thing. Fortunately, many of these libraries allow you to selectively choose which zones you want to support, making the data size much more palatable.

There are six libraries for this that I am aware of:

Moment-timezone is an extension to moment.js, and is quite stable and functional. (As a collaborator, I am biased towards this library, but I do believe it to be the most appropriate choice for most modern development.)

js-joda is a JavaScript implementation of the Joda-Time API (from Java), and includes time zone support through a separate module.

BigEasy/TimeZone also appears to be on the right track.

TimeZoneJS has been around the longest, but is known to have some long-standing bugs, especially near daylight saving time transitions. Hopefully these will be fixed at some point in the future.

You should evaluate these libraries to see which will meet your needs. If unsure, go with moment/moment-timezone.

If you can limit your usage to modern web browsers, you can now do the following without any special libraries:

new Date().toLocaleString("en-US", {timeZone: "America/New_York"})

This isn't a comprehensive solution, but it works for many scenarios that require only output conversion (from UTC or local time to a specific time zone, but not the other direction). This is part of the ECMAScript Internationalization API (ECMA-402). See this post for more details. This compatibility table tracks which versions are supported.

When you do this in the Firebug console: var date_time = new Date(), the value of date_time is (for me in AEST) Date {Sun Aug 21 2016 22:18:47 GMT+1000 (AEST)} and so therefore it seems it has stored a timezone. How can I ensure date_time is purely the UTC time, without any timezone included?

@user1063287the toString method uses the host timezone offset to produce a date and time in the "local" time zone. The date object itself has a time value that is an offset from 1970-01-01T00:00:00Z, so effectively UTC. To see the UTC date and time, use toISOString.

How to initialize javascript date to a particular timezone - Stack Ove...

javascript timezone
Rectangle 27 45

Can someone explain how Date.UTC works

Date.UTC creates a timevalue for the provided year, month, date, etc. without any offset. So if the client machine is set for, say, UTC +05:00 then:

var d = new Date(Date.UTC(2013, 11, 30, 12, 0, 0));

You can't set the timezone, however you can use UTC values to create a date object, adjust the hours and minutes for the offset, then use the UTC methods to get the date and time components for the countdown.

function z(n){return (n < 10? '0' : '') + n;}

var d = new Date(Date.UTC(2012, 11, 30, 12, 0, 0));

d.setUTCHours(d.getUTCHours() - 7);

alert(d.getUTCFullYear() + '-' + z(d.getUTCMonth() + 1) + '-' + 
      z(d.getUTCDate()) + 'T' + z(d.getUTCHours()) + ':' +
      z(d.getUTCMinutes()) + ':' + z(d.getUTCSeconds()) + '-07:00'
);

// 2012-12-30T05:00:00-07:00

If nonUTC methods are used, the local offset will affect the result.

Rob, When formatting an ISO8601 date string, you should not include the characters "UTC" in the output.

I may be missing something here but why is Date.UTC(2013, 11, 30, 12, 0, 0) in December? Shouldn't it be in November?

How do I specify the time zone when creating a JavaScript Date? - Stac...

javascript date datetime utc
Rectangle 27 7

My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.

JavaScript can treat two equal dates in different formats differently.

new Date('date as text');

Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).

var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');

var date = new Date(year, month, dayOfMonth);

var offsetInMs = ((date.getTimezoneOffset() * 60)  // Seconds
                 * 1000);                          //  Milliseconds

var utcDate = new Date(date.getTime + offsetInMs);

Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.

How do you convert a JavaScript date to UTC? - Stack Overflow

javascript date utc
Rectangle 27 7

My recommendation when working with dates is to parse the date into individual fields from user input. You can use it as a full string, but you are playing with fire.

JavaScript can treat two equal dates in different formats differently.

new Date('date as text');

Once you have your date parsed into its individual fields from user input, create a date object. Once the date object is created convert it to UTC by adding the time zone offset. I can't stress how important it is to use the offset from the date object due to DST (that's another discussion however to show why).

var year = getFullYear('date as text');
var month = getMonth('date as text');
var dayOfMonth = getDate('date as text');

var date = new Date(year, month, dayOfMonth);

var offsetInMs = ((date.getTimezoneOffset() * 60)  // Seconds
                 * 1000);                          //  Milliseconds

var utcDate = new Date(date.getTime + offsetInMs);

Now you can pass the date to the server in UTC time. Again I would highly recommend against using any date strings. Either pass it to the server broken down to the lowest granularity you need e.g. year, month, day, minute or as a value like milliseconds from the unix epoch.

How do you convert a JavaScript date to UTC? - Stack Overflow

javascript date utc
Rectangle 27 29

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}
>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]
>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']
__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

If you print the date like datetime.datetime.utcnow().isoformat()[:-3]+"Z" it will be exactly like what JSON.stringify() produces in javascript

JSON datetime between Python and JavaScript - Stack Overflow

javascript python json
Rectangle 27 29

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}
>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]
>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']
__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

If you print the date like datetime.datetime.utcnow().isoformat()[:-3]+"Z" it will be exactly like what JSON.stringify() produces in javascript

JSON datetime between Python and JavaScript - Stack Overflow

javascript python json
Rectangle 27 29

Here's a fairly complete solution for recursively encoding and decoding datetime.datetime and datetime.date objects using the standard library json module. This needs Python >= 2.6 since the %f format code in the datetime.datetime.strptime() format string is only supported in since then. For Python 2.5 support, drop the %f and strip the microseconds from the ISO date string before trying to convert it, but you'll loose microseconds precision, of course. For interoperability with ISO date strings from other sources, which may include a time zone name or UTC offset, you may also need to strip some parts of the date string before the conversion. For a complete parser for ISO date strings (and many other date formats) see the third-party dateutil module.

Decoding only works when the ISO date strings are values in a JavaScript literal object notation or in nested structures within an object. ISO date strings, which are items of a top-level array will not be decoded.

date = datetime.datetime.now()
>>> json = dumps(dict(foo='bar', innerdict=dict(date=date)))
>>> json
'{"innerdict": {"date": "2010-07-15T13:16:38.365579"}, "foo": "bar"}'
>>> loads(json)
{u'innerdict': {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)},
u'foo': u'bar'}
>>> json = dumps(['foo', 'bar', dict(date=date)])
>>> json
'["foo", "bar", {"date": "2010-07-15T13:16:38.365579"}]'
>>> loads(json)
[u'foo', u'bar', {u'date': datetime.datetime(2010, 7, 15, 13, 16, 38, 365579)}]
>>> json = dumps(['foo', 'bar', date])
>>> json
'["foo", "bar", "2010-07-15T13:16:38.365579"]'
>>> loads(json)
[u'foo', u'bar', u'2010-07-15T13:16:38.365579']
__all__ = ['dumps', 'loads']

import datetime

try:
    import json
except ImportError:
    import simplejson as json

class JSONDateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime)):
            return obj.isoformat()
        else:
            return json.JSONEncoder.default(self, obj)

def datetime_decoder(d):
    if isinstance(d, list):
        pairs = enumerate(d)
    elif isinstance(d, dict):
        pairs = d.items()
    result = []
    for k,v in pairs:
        if isinstance(v, basestring):
            try:
                # The %f format code is only supported in Python >= 2.6.
                # For Python <= 2.5 strip off microseconds
                # v = datetime.datetime.strptime(v.rsplit('.', 1)[0],
                #     '%Y-%m-%dT%H:%M:%S')
                v = datetime.datetime.strptime(v, '%Y-%m-%dT%H:%M:%S.%f')
            except ValueError:
                try:
                    v = datetime.datetime.strptime(v, '%Y-%m-%d').date()
                except ValueError:
                    pass
        elif isinstance(v, (dict, list)):
            v = datetime_decoder(v)
        result.append((k, v))
    if isinstance(d, list):
        return [x[1] for x in result]
    elif isinstance(d, dict):
        return dict(result)

def dumps(obj):
    return json.dumps(obj, cls=JSONDateTimeEncoder)

def loads(obj):
    return json.loads(obj, object_hook=datetime_decoder)

if __name__ == '__main__':
    mytimestamp = datetime.datetime.utcnow()
    mydate = datetime.date.today()
    data = dict(
        foo = 42,
        bar = [mytimestamp, mydate],
        date = mydate,
        timestamp = mytimestamp,
        struct = dict(
            date2 = mydate,
            timestamp2 = mytimestamp
        )
    )

    print repr(data)
    jsonstring = dumps(data)
    print jsonstring
    print repr(loads(jsonstring))

If you print the date like datetime.datetime.utcnow().isoformat()[:-3]+"Z" it will be exactly like what JSON.stringify() produces in javascript

JSON datetime between Python and JavaScript - Stack Overflow

javascript python json
Rectangle 27 2

I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

var myDate = new Date(myReceivedDate);

Here is my complete solution minus Steve Levithan's source, which you can download:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}
<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

If you can specify the format of the date, then you should use ISO 8601 extended as that's the only format that ECMA-262 requires support for.

javascript - ASP.NET MVC JsonResult Date Format - Stack Overflow

javascript asp.net-mvc json
Rectangle 27 2

I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

var myDate = new Date(myReceivedDate);

Here is my complete solution minus Steve Levithan's source, which you can download:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}
<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

If you can specify the format of the date, then you should use ISO 8601 extended as that's the only format that ECMA-262 requires support for.

javascript - ASP.NET MVC JsonResult Date Format - Stack Overflow

javascript asp.net-mvc json
Rectangle 27 3

A time zone is not the same as a time zone offset. One cannot just take the number -8 and assume that the time zone should be Pacific time.

Offsets can change within a single time zone. For example, Pacific Time usually uses -8, but switches to -7 when daylight saving time is in effect.

The offsets in the DisplayName property of a TimeZoneInfo are only the standard offset. They match with the BaseOffset property. They do not change to reflect the current offset.

Time zone detection in JavaScript is imperfect. There are only three approaches:

The problem is, if when I change timezone of client machine to (UTC -8:00), the client machine shows the timezone name as "(UTC-08:00) Pacific Time (US & Canada)" but in application the timezone differs from the client system it shows as "(UTC-08:00) Baja California".

This is probably related to how you are choosing a time zone in your application code. It sounds to me like you're scanning the list of server time zones and choosing the first one that matches some criteria. Since both of these time zones have the same base offset, you're probably just picking the wrong one, and you shouldn't be doing that anyway. But since you didn't show that part of your code, I can't help you much there.

Whether the TimeZoneInfo class can work automatically work according to the adjusment rule, when we convert from UTC to Local?

Yes, it can. There's nothing wrong with TimeZoneInfo, it's all about how you're using it. You probably are selecting the wrong time zone.

Do we have to detect the DST for particular datetime using the method TimeZoneInfoObject.IsDaylightSavingTime(DateTime) and do conversion?

No, you should not have to do that just to convert from UTC to a specific time zone. The ConvertTimeFromUtc function will handle that for you.

Is there any other classes in .Net which can sync with windows timezones?

TimeZoneInfo is the only one built in to the .NET Framework. Noda Time is a great alternative that can work with either Windows time zone or IANA time zones.

Lastly, I'll re-iterate what Jon said in comments. If all you're doing is displaying a particular instant in time to an end-user, then forget about time zone detection or working with local time on the server at all. Just send the UTC time to the client, and use either the UTC functions on the JavaScript Date object, or use a library like moment.js. Either can work in both UTC and local, and can convert between them. For example (using moment.js):

var valueFromServer = "2015-07-26T12:00:00Z";     // the Z means UTC
var localTime = moment(valueFromServer).format(); // "2015-07-26T05:00:00-07:00"  (Pacific)

c# - Daylight Saving Time not working in TimeZoneInfo, when converting...

c# asp.net sql-server timezone dst
Rectangle 27 4

// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(city, offset) {

    // create Date object for current location
    d = new Date();

    // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);

    // create new Date object for different city
    // using supplied offset
    nd = new Date(utc + (3600000*offset));

    // return time as a string
    return "The local time in " + city + " is " + nd.toLocaleString();

}

this function is useful to calculate time zone value by providing name of a city/country and offset value

php - How to change the date in javascript having different timezones ...

javascript php date datetime timestamp-with-timezone
Rectangle 27 18

I would recommend to always use UTC (GMT) time on the server side (in code-behind, database, etc), and convert time from UTC to local time for display purposes only. This means that all time manipulations - including saving time in database, performing calculations, etc - should be be done using UTC.

The problem is: how does your code-behind know what is the time zone of the client browser? Say the user enters some date/time value (such as 12/30/2009 14:30) in the form and submits it to the server. Assuming that the user submitted local time, how does the server know how to convert this value to UTC?

The application can ask the user to specify the time zone (and save it in a persistent cookie or database), but it requires and extra effort from the user, and your app would need to implement the logic and screens for this. It would be nicer if the app could determine client's time zone automatically.

I have addressed this issue with the help of JavaScript's getTimezoneOffset function, which is the only API that can tell the server about the time difference between local time on the client and GMT. Since this is a client-side API, I did the following: on the server side check for a custom session cookie holding the time offset value, and if it's not available, reload the page (only during GET, and not POST, calls) with some JavaScript logic added to generate the time offset and save it in the cookie. From the client-side this is almost transparent (once during session I reload a page on GET). Once I have the offset in the cookie, I apply it to the time management functions depending on direction of time conversion (UTC to local time, or local time to UTC).

This may sound a bit complicated, and it is, but after I wrote helper functions, integrating this feature in the site was a matter of making a single call in Page_Load (of pages that needed time conversion), and using time conversion routines when sending and retrieving time values to and from the browser. Here is an example of how it can be used:

using My.Utilities.Web;
...

// Derive the form class from BaseForm instead of Page.
public class WebForm1: BaseForm
{
...
private void Page_Load(object sender, System.EventArgs e)
{
  // If we only want to load the page to generate the time
  // zone offset cookie, we do not need to do anything else.
  if (InitializeLocalTime())
    return;

  // Assume that txtStartDate is a TextBox control.
  if (!IsPostback)
  {
     // To display a date-time value, convert it from GMT (UTC)
     // to local time.
     DateTime startDate = GetStartDateFromDB(...);
     txtStartDate.Text  = FormatLocalDate(startDate);
     ...
  }
  else
  {
     // To save a date-time value, convert it from local
     // time to GMT (UTC).
     DateTime tempDate  = DateTime.Parse(txtStartDate.Text);
     DateTime startDate = ConvertLocalTimeToUtc(tempDate);
     SaveStartDateInDB(startDate, ...);
     ...
  }
}
...
}

If you need more specifics, check out the Its About Time: Localizing Time in ASP.NET Applications article (sorry, but I do not have a direct link to the article on the publisher's site, since asp.netPRO restricts access to paid subscribers only; there are links to PDF copies, though). I wish I could post the sample from the article, but I don't want to violate the copyright; however, here is a project to build a helper library that has all necessary functionality and documentation (just ignore the stuff you do not need).

UPDATE: The article has been posted online with sample project by the new publisher here.

I disagree with the statement that your app should determine user's timezone automatically. Users can set any timezone/date/time they want in theirs operating system and bypass your business rules. Never trust user input.

I don't understand your point Bruno. First, there are no business rules associated with time zones. It's an issue of usability. We could've used GMT, but it's not convenient for users, so we use local time. If user changes the system clock (or whatever way they use to specify time zone), who cares? I don't see a problem here. I'm also not following a transition from your first statement to the second statement. Do you not like the "automatic" part, or do you not like the idea of using local time at all (if it's not done automatically, user must be able to change it somehow, right)?

+1. @BrunoSalvino, how would you suggest to pass the timezone data? The other way I can think of doing this is providing an explicit user input. The latter is even less trustworthy than the automatic solution proposed here, as the user is more likely to make mistake. From user's perspective this will require timezone inputs, which is not user-friendly especially when the page does not even require a date-time information, but still has to persist the date and time of certain user interaction (like the time the user uploaded some file or did a financial transaction).

c# - How to work with time zones in ASP.NET? - Stack Overflow

c# asp.net timezone reminders
Rectangle 27 54

A Date object's underlying value is actually in UTC. To prove this, notice that if you type new Date(0) you'll see something like: Wed Dec 31 1969 16:00:00 GMT-0800 (PST). 0 is treated as 0 in GMT, but .toString() method shows the local time.

Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.

var _date = new Date(1270544790922); 
// outputs > "Tue Apr 06 2010 02:06:30 GMT-0700 (PDT)", for me
_date.toLocaleString('fi-FI', { timeZone: 'Europe/Helsinki' });
// outputs > "6.4.2010 klo 12.06.30"
_date.toLocaleString('en-US', { timeZone: 'Europe/Helsinki' });
// outputs > "4/6/2010, 12:06:30 PM"

This works but.... you can't really use any of the other date methods for your purposes since they describe the user's timezone. What you want is a date object that's related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it's methods.

moment(1270544790922).tz('Europe/Helsinki').format('YYYY-MM-DD HH:mm:ss')
// outputs > 2010-04-06 12:06:30
moment(1270544790922).tz('Europe/Helsinki').hour()
// outputs > 12

Option 2 - Hack up the date object

var currentHelsinkiHoursOffset = 2; // sometimes it is 3
var date = new Date(1270544790922);
var helsenkiOffset = currentHelsinkiHoursOffset*60*60000;
var userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var helsenkiTime = new Date(date.getTime()+ helsenkiOffset + userOffset);
// Outputs > Tue Apr 06 2010 12:06:30 GMT-0700 (PDT)

It still thinks it's GMT-0700 (PDT), but if you don't stare too hard you may be able to mistake that for a date object that's useful for your purposes.

I conveniently skipped a part. You need to be able to define currentHelsinkiOffset. If you can use date.getTimezoneOffset() on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.

Conclusion - I think especially for this purpose you should use a date library like moment-timezone.

also... a similar task can be done, by simply using the gmt offset from one location. You don't need javascript at all in that case.

sorry but no, I mean the exact opposite :) I edited the question, maybe it is clearer now

Unfortunately that's the only thing that I also came up with. I thought that maybe browser could generate "_helsinkiOffset" for me.

I believe *60*60 should instead be *60000, as getTime is in milliseconds and getTimezoneOffset is in minutes, of which there are 60000 milliseconds in a minute, not 60*60==3600

javascript - How to ignore user's time zone and force Date() use speci...

javascript date timezone
Rectangle 27 14

To account for milliseconds and the user's time zone, use the following:

var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable

To replace using a fixed offset for central, I used the concept of creating a date using CST with a fixed time of 00:00, then getUTCHHours of that date.

+1 This worked for me. Not sure how 'the' answer can work without dealing in milliseconds.

@Ehren shouldn't you add the timezoneOffset to get to gmt and then subtract the central offset?

javascript - How to ignore user's time zone and force Date() use speci...

javascript date timezone
Rectangle 27 10

function parseTimestamp(timestampStr) {
  return new Date(new Date(timestampStr).getTime() + (new Date().getTimezoneOffset() * 60 * 1000));
};

//Sun Jan 01 2017 12:00:00
var timestamp = 1483272000000;
date = parseTimestamp(timestamp);
document.write(date);

javascript - How to ignore user's time zone and force Date() use speci...

javascript date timezone
Rectangle 27 2

How the time is stored in your database isn't relevant. It matters only how the time is transmitted over your API and into FullCalendar. Assuming the exact string you provided "2013-06-30T16:00:00.000Z" is what is passed into FullCalendar, then the behavior you described makes sense. The UTC time you provided is being adjusted to the user's local time zone.

FullCalendar displays a calendar in the local time zone of the person who is viewing it. There is no setting to view the calendar in UTC, or in any other time zone. There is some information here where they mention being "timezone agnostic". You can think of it this way in terms of how the calendar is drawn, but you will always still have the local time zone when looking at any Date object, because that's how JavaScript works.

You have some options:

  • Set the ignoreTimezone option to true, and pass your input values in as strings rather than dates.
  • Pass the values as strings with the correct time zone offset for the person viewing the data.
  • Pass the values as Date objects that have already been adjusted for the local time zone.

The currentTimezone option is not part of FullCalendar. It's in the gcal.js addon, for hooking FullCalender up to Google Calendar over the gcal 1.0 api. It simply passes that parameter to Google as ctz in the querystring. It only affects the way the data is returned from Google. It doesn't do anything in FullCalendar itself.

I have set ignoreTimezone all to true, tried removing Z from the timezone offset but both do not work. When i dropped my event into the calendar on day 16, it is written as day 15 in my database already - @Matt Johnson

The problem may lie on the server side. Please show us exactly the value coming out of this code, and how it is being received and stored in the database. (edit your question)

hi, i edited the code

javascript - FullCalendar Date differs when stored and retrieved from ...

javascript jquery html time fullcalendar
Rectangle 27 16

Don't rely on JavaScript's Date constructor to parse a string. The behavior and supported formats vary wildly per browser and locale. Here are just some of the default behaviors if you use the Date object directly.

If you must come from a string, try using a standardized format such as ISO8601. The date you gave in that format would be "2012-06-25T12:00:00". The easiest way to work with these in JavaScript is with moment.js.

Also, be careful about what you are actually meaning to represent. Right now, you are passing a local date/time, saving a local/date/time, and returning a local date/time. Along the way, the idea of what is "local" could change.

In many cases, the date/time is intended to represent an exact moment in time. To make that work, you need to convert from the local time entered to UTC on the client. Send UTC to your server, and store it. Later, retrieve UTC and send it back to your client, process it as UTC and convert back to local time. You can do all of this easily with moment.js:

// I'll assume these are the inputs you have.  Adjust accordingly.
var dateString = "6-25-2012";
var timeString = "12:00:00 PM";

// Construct a moment in the default local time zone, using a specific format.
var m = moment(dateString + " " + timeString, "M-D-YYYY h:mm:ss A");

// Get the value in UTC as an ISO8601 formatted string
var utc = m.toISOString(); // output: "2012-06-25T19:00:00.000Z"

On the server in .Net:

var dt = DateTime.Parse("2012-06-25T19:00:00.000Z",   // from the input variable
                        CultureInfo.InvariantCulture, // recommended for ISO
                        DateTimeStyles.RoundtripKind) // honor the Z for UTC kind

Store that in the database. Later retrieve it and send it back:

// when you pull it from your database, set it to UTC kind
var dt = DateTime.SpecifyKind((DateTime)reader["yourfield"], DateTimeKind.Utc);

// send it back in ISO format:
var s = dt.ToString("o"); // "o" is the ISO8601 "round-trip" pattern.

Pass it back to the javascript in moment.js:

// construct a moment:
var m = moment("2012-06-25T19:00:00.000Z"); // use the value from the server

// display it in this user's local time zone, in whatever format you want
var s = m.format("LLL");   // "June 25 2012 12:00 PM"

// or if you need a Date object
var dt = m.toDate();

See - that was easy, and you didn't need to get into anything fancy with time zones.

To store that ISO string in the database, doesn't the column have to be a datetimeoffset field (vs. a datetime SQL field)? Assuming of course we're not storing just a string. Or is it preferable to just store the string?

No, don't store a string. If you are storing UTC, you can use either datetime or datetime2. You don't need a datetimeoffset for this particular scenario. You could use it, but you probably don't need to unless you care about the users local time zone. See my answer on DateTime vs DateTimeOffset.

Just to add to my previous comment - many people do actually prefer to use DateTimeOffset for UTC. Even though they know the offset is always zero, tracking that in a DateTimeOffset instead of a DateTime is a good way to prevent it from accidently being interpreted incorrectly. The only downside to this is that it will be serialized with +00:00 instead of Z, but that's often acceptable.

datetime - How do you preserve a JavaScript date's time zone from brow...

javascript datetime timezone
Rectangle 27 3

You can easily take care of the timezone offset by using the getTimezoneOffset() function in Javascript. For example,

var dt = new Date(1458619200000);
console.log(dt); // Gives Tue Mar 22 2016 09:30:00 GMT+0530 (IST)

dt.setTime(dt.getTime()+dt.getTimezoneOffset()*60*1000);
console.log(dt); // Gives Tue Mar 22 2016 04:00:00 GMT+0530 (IST)

var offset = -300; //Timezone offset for EST in minutes.
var estDate = new Date(dt.getTime() + offset*60*1000);
console.log(estDate); //Gives Mon Mar 21 2016 23:00:00 GMT+0530 (IST)

Though, the locale string represented at the back will not change. The source of this answer is in this post. Hope this helps!

is your unix time always in EST timezone? If so then you need to add the correct GMT offset for your input (-4 hours), then translate THAT to the local time zone by adding the local timezoneoffset() back into the unix time before creating a new date object.

what are you setting the time to, utc? how do I set it to a specific timezone

@foreyez From the UTC time, its easy to convert to any fixed timezone. You can simply add or subtract the timezone offset in the date object by using setTime(). For example, if your fixed timezone is UTC+10 (Australian Eastern Standard Time), +600*60*1000 will be the offset you can add to your time.

javascript - How to set date always to eastern time regardless of user...

javascript datetime timezone