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.
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'm located in PST timezone and I want to be able to take the string "2014-01-01" and convert it into Unix time without "2014-01-01" getting converted to PST.
Here's what I'm doing:
Date.parse(new Date("2014-01-01"))
I'm getting the value 1388534400000 which is equivalent to Tue Dec 31 2013 16:00:00 GMT-0800 (Pacific Standard Time)
I want to take the date as "2014-01-01" and not convert it into PST before converting it into Unix time.
A few things:
The Date constructor returns a Date object, not a string. You shouldn't wrap it in a call to Date.parse.
If you want a unix timestamp, just call getTime().
var ts = new Date("2014-01-01").getTime();
Alternatively, you can parse the date string without creating a Date object at all.
var ts = Date.parse("2014-01-01");
The behavior of date parsing in JavaScript is implementation dependent. Most browsers will already interpret a yyyy-mm-dd string to be in UTC, due to the dashes (-). If you replace with with slashes (/), you'll see the string get interpreted as local time instead.
I think you're confused about the output. You said the timestamp was equivalent to PST, but that's just one representation. It's also equivalent to the UTC value you passed in. It's not getting converted in the input, it's being converted when you are converting the timestamp back to local time.
You can use a library like moment.js, which gives you full control of the input and output. This is usually the best option, but has the overhead of including a library in your application.
Another way to convert the specified date string to Unix time is as follows:
var str = "2014-01-01";
var parts = str.split('-');
parts[1] -= 1; // js numeric mos are 0-11
var ms = Date.UTC( parts[0], parts[1], parts[2] ); // parts: YYYY, MM, DD
var unix_time = ms/1000; // Unix time uses seconds
console.log("Unix time: " + unix_time);
Date.UTC() returns the number of milliseconds occurring since January 1, 1970 midnight up to the instant of the specified date, irrespective of any timezone. The script transforms the result into Unix time, i.e. seconds, by dividing the number of milliseconds by 1000.
After splitting the string into an array, the code adjusts the element containing the month, lest JavaScript mistake its value for March; JavaScript comprehends numeric months as ranging from 0-11, not 1-12. Next, the script passes the elements sequentially in accordance with the year, month, day parameters that Date.UTC requires. Although UTC() expects numbers for parameters, it accepts the numerical strings.
Note: if you first create a new date object and expect to use a UTC method -- that results in an error because it is a static method of JavaScript's Date Object.
You may check the validity of the UTC() return value, using the aforementioned variables ms and str, as follows:
console.log( new Date( str ).toUTCString( ms ));
The output: Wed, 01 Jan 2014 00:00:00 GMT
See live demo here)
Passing a date string to the Date constructor instead of the numerical parameters it expects affords an unexpected benefit; the date string is treated as if it's timezone is UTC, i.e. zero by the local date object. Once created, the local date object executes its toUTCString() method to attain the above-indicated result. The toString() method would also yield the same output, but it appends local timezone information.