The following outputs a time that is 4 hours less than what was input:
X = new Date('2015-07-09T14:18:12.430')
$('body').append(X)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The following outputs a time that is 4 hours less than what was input:
X = new Date('2015-07-09T14:18:12.430')
$('body').append(X)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
When you omit the timezone information on the end of an ISO 8601 formatted date-time the majority of computer implementations default to +0000
, this means Date interprets 2015-07-09T14:18:12.430
the same as 2015-07-09T14:18:12.430+0000
or 2015-07-09T14:18:12.430Z
It looks like you were expecting it to be interpreted as your local time rather than in UTC, you have 3 options
function myParser(iso_style) {
var d = new Date(iso_style);
return new Date(
d.getUTCFullYear(),
d.getUTCMonth(),
d.getUTCDate(),
d.getUTCHours(),
d.getUTCMinutes(),
d.getUTCSeconds(),
d.getUTCMilliseconds()
);
}
You can't simply adjust by your local offset as you would experience unexpected behaviour if the time crosses a date that would change that offset e.g. a daylight savings boundry
As Salman A's answer points out the current ES 6 Draft defines that an omitted timezone should be interpreted as meaning the client's local timezone. This will make the behaviour inconsistent as different JavaScript implementations change over so I strongly recommend you always use a timezone when writing ISO 8601.
When you do no specify the timezone:
ECMAScript-5 compliant browsers will assume UTC timezone:
The value of an absent time zone offset is "
Z
".
ECMAScript-6 compliant browsers will assume local timezone:
If the time zone offset is absent, the date-time is interpreted as a local time.
Use the long Date constructor which assumes local timezone:
var X = new Date(2015, 7 - 1, 9, 14, 18, 12, 430);
alert(X);
A quick and dirty workaround:
X = new Date('2015-07-09T14:18:12.430');
$('body').append( X.toString().split('GMT')[0] );
It works by turning the date object into a string, then splitting it into an array around the pattern GMT
. So you would have 2 elements in the array: Thu Jul 09 2015 10:18:12
and 0400 (EDT)
. Since you want to drop everything after the GMT, you just use the element in the 0 index of the array
I misunderstood the question. If you use X.toUTCString(), it may fix your issue.