Seems there is a problem with definition of ISO date format in Javascript. As far as I undrerstand ISO-formatted date can include TZ offset that includes hours, minutes and seconds, e.g.:
1919-07-01T00:00:00+04:31:19
Trying to parse such datetime string using JavaScript new Date() object leads to an error:
new Date('1919-07-01T00:00:00+04:31:17').toLocaleDateString('ru-RU') => "Invalid Date"
new Date('1919-07-01T00:00:00+04:31').toLocaleDateString('ru-RU') => "01.07.1919"
The date specified in the example comes from the Java backend client/POSTGRESQL database where representation '1919-07-01T00:00:00+04:31:17' treated as a valid ISO date.
The reason the date contains "seconds" in timezone offset is understood if we look as the following data regaring daylight savings changes:
https://www.timeanddate.com/time/change/russia/moscow?year=1919
Is there any suggestion why it is impossible to overcome this limitation or where is the origin of the problem?
Seems there is a problem with definition of ISO date format in Javascript.
Javascript is based on ECMA-262, which is published by ECMA International. ISO 8601 is published by ISO, a different standards organisation. I don't have a full copy of ISO 8601, however I expect that there are extensions to allow seconds in the offset given they were fairly common prior to 1900.
ECMA-262 defines a couple of formats, one is based on a simplification of ISO 8601, so does not support all of the formats ISO 8601 does (the other is the format produced by toString).
Since the format in the OP is not consistent with one of the formats in ECMA-262, parsing is implementation dependent, see Why does Date.parse give incorrect results?
Your best option is to manually parse the string, either with a simple function or a library that supports seconds in the offset.
An example parse function is below (according to timeanddate the seconds part of the offset in 1919 should have been 19, not 17 so I've modified the original string accordingly):
// Parse format 1919-07-01T00:00:00+04:31:19
function parseWithTZSecs(date) {
let [Y, M, D, H, m, s, oH, om, os] = date.match(/\d+/g);
let sign = date.substring(19,20) == '+'? -1 : 1;
return new Date(Date.UTC(Y, M-1, D, +H + sign*oH, +m + sign*om, +s + sign*os));
}
let date = parseWithTZSecs('1919-07-01T00:00:00+04:31:19');
// 1919-07-01, 12:00:00 AM
console.log(date.toLocaleString('en-CA',{timeZone: 'Europe/Moscow'}));
This is just an example, of course it should do validation of input and deal with unexpected formats and values.
Related
This question already has answers here:
How to ISO 8601 format a Date with Timezone Offset in JavaScript?
(21 answers)
Javascript date format like ISO but local
(12 answers)
Closed last year.
Hi i have a date that arrive with this format 2020-05-25T20:11:38Z, and i need to convert to 2020-05-25T21:11:38+01:00.
In my project is not installed moment.js is a big project, and the masters don't use it.
is there some where to make this change?
I have the timeZone for every zone.
I know that there is options like this getTimezoneOffset();
And i did find in stackoverflow, but i didn't find any response in javascript to change zulu to utc with offset.
Thanks for your indications
The format "2020-05-25T20:11:38Z" is a common standard ISO 8601 format, it is also produced by the default Date.prototype.toString method, however it's only with a UTC (+0) offset.
The above ISO 8601 format is reliably parsed by reasonably current built–in parsers (some very old implementations won't parse it correctly), so to get a Date object:
let date = new Date('2020-05-25T20:11:38Z');
Formatting it for a fixed +1 offset can done by adjusting the Date for the offset then formatting it as required by leveraging the default toISOString method, e.g.
// Initial timestamp
let s = '2020-05-25T20:11:38Z'
// Convert s to a Date
let d = new Date(s);
// Show that it's the same date
console.log(`Initial value: ${s}\n` +
`Parsed value : ${d.toISOString()}`);
// Create a new date with 1 hour added as 3,600,000 milliseconds
let e = new Date(d.getTime() + 3.6e6);
// Format and manually modify the offset part
let timestamp = e.toISOString().replace('Z','+01:00');
console.log(`Adjusted timestamp: ${timestamp}`);
// Parse back to date
console.log(`Parsed to a Date : ${new Date(timestamp).toISOString()}`);
The resulting timestamp can be parsed back to a Date that represents the same instant in time as the original string (last line).
Note that the adjusted Date is only created for the sake of formatting the timestamp, it shouldn't be used for anything else.
If, on the other hand, you want a general function to format dates as ISO 8601 with the local offset, there is likely an answer at Javascript date format like ISO but local that suits. If so, then this is a duplicate, e.g. this answer or this one.
Also, there are a number of libraries that will allow specifying the formatting and timezone as separate parameters, so consider using one if you're going to do a lot of date formatting or manipulation.
I have a string representing the current time: 2015-11-24T19:40:00. How do I parse this string in Javascript to get a Date represented by this string as the LOCAL TIME? Due to some restriction, I cannot use the library moment, but jquery is allowed. I know that someone has asked this question before, but the answer used moment
For example, if I run the script in California, then this string would represent 7PM pacific time, but if I run the script in NY then this string would represent Eastern Time?
I tried the following but Chrome and Firefox give me different results:
var str = "2015-11-24T19:40:00";
var date = new Date(str);
Chrome consumes it as UTC time (Tue Nov 24 2015 11:40:00 GMT-0800 (Pacific Standard Time)),
but Firefox consumes it as my local PACIFIC time (Tue Nov 24 2015 19:40:00 GMT-0800 (Pacific Standard Time))
I tried adding "Z" to str, like this var date = new Date(str+"Z");, then both browsers give me UTC time. Is there any similar letter to "Z" which tells all browsers (at least chrome, Firefox and Safari) to parse the string as local time zone?
Parsing of date strings using the Date constructor or Date.parse (which are essentially the same thing) is strongly recommended against.
If Date is called as a function and passed an ISO 8601 format date string without a timezone (such as 2015-11-24T19:40:00), you may get one of the following results:
Pre ES5 implementaitons may treat it as anything, even NaN (such as IE 8)
ES5 compliant implementations will treat it as UTC timezone
ECMAScript 2015 compliant implementations will treat it as local (which is consistent with ISO 8601)
A Date object has a time value which is UTC, and an offset based on system settings. When you send a Date to output, what you see is usually the result of Date.prototype.toString, which is an implementation dependent, human readable string representing the date and time, usually in a timezone based on system settings.
The best way to parse date strings is to do it manually. If you are assured that the format is consistent and valid, then parsing an ISO format string as a local date is as simple as:
/* #param {string} s - an ISO 8001 format date and time string
** with all components, e.g. 2015-11-24T19:40:00
** #returns {Date} - Date instance from parsing the string. May be NaN.
*/
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISOLocal('2015-11-24T19:40:00'));
Note that parsing of ISO strings using Date.parse only accepts UTC, it does not accept any other timezone designation (noting the above behaviour if it's missing).
A variation on RobG's terrific answer.
Note that this will require that you run bleeding edge JavaScript as
it relies on the arrow notation and spread operator.
function parseDateISOString(s) {
let ds = s.split(/\D/).map(s => parseInt(s));
ds[1] = ds[1] - 1; // adjust month
return new Date(...ds);
}
Note that this doesn't take into account if the date/time given is in any timezone. It will assume local time. You can change new Date for Date.UTC to assume UTC.
There are technical reasons for why you would write you code like this. For example, here we apply the correct number of arguments, with their corresponding expected type. It's true that the Date constructor will turn strings into numbers but what could be happening is that there's a deoptimization taking place where the optimized code is expecting a number but sees a string and takes a slower path. Not a big deal but I try to write my JavaScript to avoid such things. We also won't be indexing outside the bounds of the array if less than 6 components can be found in the string which is also one of those things you can do in JavaScript but it has subtle deoptimization caveats.
Where Date is called as a constructor with more than one argument, the specified arguments represent local time.
I also have a much faster way than using the string.split() because we already know where the numbers are:
return new Date(Number(date.substring(0, 4)), Number(date.substring(5, 7))-1,
Number(date.substring(8, 10)), Number(date.substring(11, 13)),
Number(date.substring(14, 16)), Number(date.substring(17, 19)));
This will work with and/or without the 'T' and 'Z' strings and still has decent performance. I added the explicit Number conversion (faster and better than parseInt) so this also compiles in TypeScript.
Number
I have a string representing the current time: 2015-11-24T19:40:00. How do I parse this string in Javascript to get a Date represented by this string as the LOCAL TIME? Due to some restriction, I cannot use the library moment, but jquery is allowed. I know that someone has asked this question before, but the answer used moment
For example, if I run the script in California, then this string would represent 7PM pacific time, but if I run the script in NY then this string would represent Eastern Time?
I tried the following but Chrome and Firefox give me different results:
var str = "2015-11-24T19:40:00";
var date = new Date(str);
Chrome consumes it as UTC time (Tue Nov 24 2015 11:40:00 GMT-0800 (Pacific Standard Time)),
but Firefox consumes it as my local PACIFIC time (Tue Nov 24 2015 19:40:00 GMT-0800 (Pacific Standard Time))
I tried adding "Z" to str, like this var date = new Date(str+"Z");, then both browsers give me UTC time. Is there any similar letter to "Z" which tells all browsers (at least chrome, Firefox and Safari) to parse the string as local time zone?
Parsing of date strings using the Date constructor or Date.parse (which are essentially the same thing) is strongly recommended against.
If Date is called as a function and passed an ISO 8601 format date string without a timezone (such as 2015-11-24T19:40:00), you may get one of the following results:
Pre ES5 implementaitons may treat it as anything, even NaN (such as IE 8)
ES5 compliant implementations will treat it as UTC timezone
ECMAScript 2015 compliant implementations will treat it as local (which is consistent with ISO 8601)
A Date object has a time value which is UTC, and an offset based on system settings. When you send a Date to output, what you see is usually the result of Date.prototype.toString, which is an implementation dependent, human readable string representing the date and time, usually in a timezone based on system settings.
The best way to parse date strings is to do it manually. If you are assured that the format is consistent and valid, then parsing an ISO format string as a local date is as simple as:
/* #param {string} s - an ISO 8001 format date and time string
** with all components, e.g. 2015-11-24T19:40:00
** #returns {Date} - Date instance from parsing the string. May be NaN.
*/
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISOLocal('2015-11-24T19:40:00'));
Note that parsing of ISO strings using Date.parse only accepts UTC, it does not accept any other timezone designation (noting the above behaviour if it's missing).
A variation on RobG's terrific answer.
Note that this will require that you run bleeding edge JavaScript as
it relies on the arrow notation and spread operator.
function parseDateISOString(s) {
let ds = s.split(/\D/).map(s => parseInt(s));
ds[1] = ds[1] - 1; // adjust month
return new Date(...ds);
}
Note that this doesn't take into account if the date/time given is in any timezone. It will assume local time. You can change new Date for Date.UTC to assume UTC.
There are technical reasons for why you would write you code like this. For example, here we apply the correct number of arguments, with their corresponding expected type. It's true that the Date constructor will turn strings into numbers but what could be happening is that there's a deoptimization taking place where the optimized code is expecting a number but sees a string and takes a slower path. Not a big deal but I try to write my JavaScript to avoid such things. We also won't be indexing outside the bounds of the array if less than 6 components can be found in the string which is also one of those things you can do in JavaScript but it has subtle deoptimization caveats.
Where Date is called as a constructor with more than one argument, the specified arguments represent local time.
I also have a much faster way than using the string.split() because we already know where the numbers are:
return new Date(Number(date.substring(0, 4)), Number(date.substring(5, 7))-1,
Number(date.substring(8, 10)), Number(date.substring(11, 13)),
Number(date.substring(14, 16)), Number(date.substring(17, 19)));
This will work with and/or without the 'T' and 'Z' strings and still has decent performance. I added the explicit Number conversion (faster and better than parseInt) so this also compiles in TypeScript.
Number
I have a string representing the current time: 2015-11-24T19:40:00. How do I parse this string in Javascript to get a Date represented by this string as the LOCAL TIME? Due to some restriction, I cannot use the library moment, but jquery is allowed. I know that someone has asked this question before, but the answer used moment
For example, if I run the script in California, then this string would represent 7PM pacific time, but if I run the script in NY then this string would represent Eastern Time?
I tried the following but Chrome and Firefox give me different results:
var str = "2015-11-24T19:40:00";
var date = new Date(str);
Chrome consumes it as UTC time (Tue Nov 24 2015 11:40:00 GMT-0800 (Pacific Standard Time)),
but Firefox consumes it as my local PACIFIC time (Tue Nov 24 2015 19:40:00 GMT-0800 (Pacific Standard Time))
I tried adding "Z" to str, like this var date = new Date(str+"Z");, then both browsers give me UTC time. Is there any similar letter to "Z" which tells all browsers (at least chrome, Firefox and Safari) to parse the string as local time zone?
Parsing of date strings using the Date constructor or Date.parse (which are essentially the same thing) is strongly recommended against.
If Date is called as a function and passed an ISO 8601 format date string without a timezone (such as 2015-11-24T19:40:00), you may get one of the following results:
Pre ES5 implementaitons may treat it as anything, even NaN (such as IE 8)
ES5 compliant implementations will treat it as UTC timezone
ECMAScript 2015 compliant implementations will treat it as local (which is consistent with ISO 8601)
A Date object has a time value which is UTC, and an offset based on system settings. When you send a Date to output, what you see is usually the result of Date.prototype.toString, which is an implementation dependent, human readable string representing the date and time, usually in a timezone based on system settings.
The best way to parse date strings is to do it manually. If you are assured that the format is consistent and valid, then parsing an ISO format string as a local date is as simple as:
/* #param {string} s - an ISO 8001 format date and time string
** with all components, e.g. 2015-11-24T19:40:00
** #returns {Date} - Date instance from parsing the string. May be NaN.
*/
function parseISOLocal(s) {
var b = s.split(/\D/);
return new Date(b[0], b[1]-1, b[2], b[3], b[4], b[5]);
}
document.write(parseISOLocal('2015-11-24T19:40:00'));
Note that parsing of ISO strings using Date.parse only accepts UTC, it does not accept any other timezone designation (noting the above behaviour if it's missing).
A variation on RobG's terrific answer.
Note that this will require that you run bleeding edge JavaScript as
it relies on the arrow notation and spread operator.
function parseDateISOString(s) {
let ds = s.split(/\D/).map(s => parseInt(s));
ds[1] = ds[1] - 1; // adjust month
return new Date(...ds);
}
Note that this doesn't take into account if the date/time given is in any timezone. It will assume local time. You can change new Date for Date.UTC to assume UTC.
There are technical reasons for why you would write you code like this. For example, here we apply the correct number of arguments, with their corresponding expected type. It's true that the Date constructor will turn strings into numbers but what could be happening is that there's a deoptimization taking place where the optimized code is expecting a number but sees a string and takes a slower path. Not a big deal but I try to write my JavaScript to avoid such things. We also won't be indexing outside the bounds of the array if less than 6 components can be found in the string which is also one of those things you can do in JavaScript but it has subtle deoptimization caveats.
Where Date is called as a constructor with more than one argument, the specified arguments represent local time.
I also have a much faster way than using the string.split() because we already know where the numbers are:
return new Date(Number(date.substring(0, 4)), Number(date.substring(5, 7))-1,
Number(date.substring(8, 10)), Number(date.substring(11, 13)),
Number(date.substring(14, 16)), Number(date.substring(17, 19)));
This will work with and/or without the 'T' and 'Z' strings and still has decent performance. I added the explicit Number conversion (faster and better than parseInt) so this also compiles in TypeScript.
Number
I want to parse date
var newDateTime = new Date(Date.parse($("#SelctedCalendarDay").val()));
$("#SelctedCalendarDay").val() value is 14-okt-2014 in string.
When the date is 14-Oct-2014 it parses it correctly.
So how can I parse this date 14-okt-2014?
I'm not sure what language you are using (Dutch?) so I'll use English, it's easy to substitute whatever language you like. You can parse a date string like 14-Oct-2014 using:
function parseDMMMY(s) {
// Split on . - or / characters
var b = s.split(/[-.\/]/);
// Months in English, change to whatever language suits
var months = {jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
jul:6, aug:7, sep:8, oct:9, nov:10, dec:11};
// Create a date object
return new Date(b[2], months[b[1].toLowerCase()], b[0]);
}
console.log(parseDMMMY('14-Oct-2014')); // Tue Oct 14 2014 00:00:00
Note that the above will create a local date object. It doesn't do any validation of values so if you give it a string like 31-Jun-2014 you'll get a Date object for 01-Jul-2014. It's easy to add validation (it takes one more line of code), but that may not be required if you know only valid strings will be passed to the function.
From the documentation of Date.parse # Mozilla
The date time string may be in ISO 8601 format. For example,
"2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can
be passed and parsed. The UTC time zone is used to interpret arguments
in ISO 8601 format that do not contain time zone information (note
that ECMAScript ed 6 draft specifies that date time strings without a
time zone are to be treated as local, not UTC).
It seems to me the native Date.parse does not convert date strings matching a specific locale. There also seem to be some slight differences between specific browsers.
Maybe you want to use a library like moment.js for that?
Or you may want to wire up some PHP strtotime to your JS.