Parse JSON (ISO8601) date string - javascript

I can create a JavaScript date object with:
var d=new Date('2012-08-07T07:47:46Z');
document.write(d);
This will write the date using the browser's time zone. But I should be able to do (no 'Z'):
var d=new Date('2012-08-07T07:47:46');
document.write(d);
This returns the same as above, but according to the ISO8601 standard, a string without a timezone (e.g. +01:00) and without 'Z', the date should be considered in the local time zone. So the second example above should write the datetime as 7:47am.
I am getting a datetime string from a server and I want to display exactly that datetime. Any ideas?

I found this script works well. It extends the Date.parse method.
https://github.com/csnover/js-iso8601/
Date.parse('2012-08-07T07:47:46');
It doesn't work on the new Date() constructor however.

You are right, Javascript doesn't play well with the ISO8601.
Use this function to convert to the desired format:
function ISODateString(d) {
function pad(n){
return n<10 ? '0'+n : n
}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
print(ISODateString(d));
Taken from: Mozilla

Related

Uncaught TypeError: time0.getHours is not a function [duplicate]

I have some code that tries to parse a date string.
When I do alert(Date("2010-08-17 12:09:36"));
It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().
When I try:
var temp = new Date("2010-08-17 12:09:36");
alert(temp);
I get an "invalid date" error.
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Date()
With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString) uses one of these formats:
"October 13, 1975 11:13:00"
"October 13, 1975 11:13"
"October 13, 1975"
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.
For More Information:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
function Animal(){
this.abc = 1;
return 1234;
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* Parse date string in format yyyy-mm-dd hh:mm:ss
** If string contains out of bounds values, an invalid date is returned
**
** #param {string} s - string to parse, e.g. "2010-08-17 12:09:36"
** treated as "local" date and time
** #returns {Date} - Date instance created from parsed string
*/
function parseDateString(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
return d && d.getMonth() == b[1] && d.getHours() == b[3] &&
d.getMinutes() == b[4]? d : new Date(NaN);
}
document.write(
parseDateString('2010-08-17 12:09:36') + '<br>' + // Valid values
parseDateString('2010-08-45 12:09:36') // Out of bounds date
);
I was having the same issue using an API call which responded in ISO 8601 format.
Working in Chrome this worked:
`
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date();
var outputDate = eventDate.toDateString();
`
but this didn't work with firefox.
Above answer helped me format it correctly for firefox:
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date(date.replace(/-/g,"/");
var outputDate = eventDate.toDateString();
You can also create single Date object and update it using the static function Date.now() :
<!doctype html>
<html> <head></head>
<body>
<h1 id="datetime"></h1>
<script>
elem_datetime = document.getElementById('datetime');
var date = new Date();
function sometimer()
{
setTimeout(sometimer, 1*1000); // wait 1 second and call again
date.setTime(Date.now());
elem_datetime.innerHTML = date.toDateString() + ' ' + date.toLocaleTimeString();
}
sometimer();
</script>
</body>
</html>
You're not getting an "invalid date" error.
Rather, the value of temp is "Invalid Date".
Is your date string in a valid format?
If you're using Firefox, check Date.parse
In Firefox javascript console:
>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000
I would try a different date string format.
Zebi, are you using Internet Explorer?
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
var temp = new Date( Date("2010-08-17 12:09:36") );
alert(temp);
the internal call to Date() returns a string that new Date() can parse.

Wrong DateTime Conversion in JS [duplicate]

I have some code that tries to parse a date string.
When I do alert(Date("2010-08-17 12:09:36"));
It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().
When I try:
var temp = new Date("2010-08-17 12:09:36");
alert(temp);
I get an "invalid date" error.
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Date()
With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString) uses one of these formats:
"October 13, 1975 11:13:00"
"October 13, 1975 11:13"
"October 13, 1975"
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.
For More Information:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
function Animal(){
this.abc = 1;
return 1234;
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* Parse date string in format yyyy-mm-dd hh:mm:ss
** If string contains out of bounds values, an invalid date is returned
**
** #param {string} s - string to parse, e.g. "2010-08-17 12:09:36"
** treated as "local" date and time
** #returns {Date} - Date instance created from parsed string
*/
function parseDateString(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
return d && d.getMonth() == b[1] && d.getHours() == b[3] &&
d.getMinutes() == b[4]? d : new Date(NaN);
}
document.write(
parseDateString('2010-08-17 12:09:36') + '<br>' + // Valid values
parseDateString('2010-08-45 12:09:36') // Out of bounds date
);
I was having the same issue using an API call which responded in ISO 8601 format.
Working in Chrome this worked:
`
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date();
var outputDate = eventDate.toDateString();
`
but this didn't work with firefox.
Above answer helped me format it correctly for firefox:
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date(date.replace(/-/g,"/");
var outputDate = eventDate.toDateString();
You can also create single Date object and update it using the static function Date.now() :
<!doctype html>
<html> <head></head>
<body>
<h1 id="datetime"></h1>
<script>
elem_datetime = document.getElementById('datetime');
var date = new Date();
function sometimer()
{
setTimeout(sometimer, 1*1000); // wait 1 second and call again
date.setTime(Date.now());
elem_datetime.innerHTML = date.toDateString() + ' ' + date.toLocaleTimeString();
}
sometimer();
</script>
</body>
</html>
You're not getting an "invalid date" error.
Rather, the value of temp is "Invalid Date".
Is your date string in a valid format?
If you're using Firefox, check Date.parse
In Firefox javascript console:
>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000
I would try a different date string format.
Zebi, are you using Internet Explorer?
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
var temp = new Date( Date("2010-08-17 12:09:36") );
alert(temp);
the internal call to Date() returns a string that new Date() can parse.

How do I format a date as ISO 8601 in moment.js?

This docs mention moment.ISO_8601 as a formatting option (from 2.7.0 - http://momentjs.com/docs/#/parsing/special-formats/), but neither of these work (even 2.7.0):
var date = moment();
date.format(moment.ISO_8601); // error
moment.format(date, moment.ISO_8601); // error
(http://jsfiddle.net/b3d6uy05/1/)
How can I get an ISO 8601 from moment.js?
moment().toISOString(); // or format() - see below
http://momentjs.com/docs/#/displaying/as-iso-string/
Update
Based on the answer: by #sennet and the comment by #dvlsg (see Fiddle) it should be noted that there is a difference between format and toISOString. Both are correct but the underlying process differs. toISOString converts to a Date object, sets to UTC then uses the native Date prototype function to output ISO8601 in UTC with milliseconds (YYYY-MM-DD[T]HH:mm:ss.SSS[Z]). On the other hand, format uses the default format (YYYY-MM-DDTHH:mm:ssZ) without milliseconds and maintains the timezone offset.
I've opened an issue as I think it can lead to unexpected results.
Use format with no parameters:
var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"
(http://jsfiddle.net/8gvhL1dz/)
Also possible with vanilla JS
new Date().toISOString() // "2017-08-26T16:31:02.349Z"
When you use Mongoose to store dates into MongoDB you need to use toISOString() because all dates are stored as ISOdates with miliseconds.
moment.format()
2018-04-17T20:00:00Z
moment.toISOString() -> USE THIS TO STORE IN MONGOOSE
2018-04-17T20:00:00.000Z
var date = moment(new Date(), moment.ISO_8601);
console.log(date);
If you just want the date portion (e.g. 2017-06-27), and you want it to work regardless of time zone and also in Arabic, here is code I wrote:
function isoDate(date) {
if (!date) {
return null
}
date = moment(date).toDate()
// don't call toISOString because it takes the time zone into
// account which we don't want. Also don't call .format() because it
// returns Arabic instead of English
var month = 1 + date.getMonth()
if (month < 10) {
month = '0' + month
}
var day = date.getDate()
if (day < 10) {
day = '0' + day
}
return date.getFullYear() + '-' + month + '-' + day
}
Answer in 2020 (Includes Timezone Support)
The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()
//** Returns now in ISO format in Central Time */
export function getNowISO() {
return `${moment().toISOString(true).substring(0, 23)}Z`
}
This will leave you with an exact ISO-formatted, localized string.
Important note: Moment now suggests using other packages for new projects.
If you need the formatting string : YYYY-MM-DDTHH:mm:ssZ
var date = moment();
console.log(date.format("YYYY-MM-DDTHH:mm:ssZ"));
var x = moment();
//date.format(moment.ISO_8601); // error
moment("2010-01-01T05:06:07", ["YYYY", moment.ISO_8601]);; // error
document.write(x);

How to format JSON date?

so, i need format JSON date from this format
"9/30/2010 12:00:00 AM", it is MM/DD/YYYY HH:MM:SS to format like this : DD/MM/YYYY, so i dont need info about hours, min and sec, and i need replace months and days from json, i tried some different ways but it always failed
i need do this using jQuery
also i didnt find any answer to formating this date type, all i found was formating date like this :/Date(1224043200000)/
so anyone have idea?
you can create a Date Object from a string like so:
var myDate = new Date(dateString);
then you can manipulate it anyway you want, one way to get your desired output is:
var output = myDate.getDate() + "\\" + (myDate.getMonth()+1) + "\\" + myDate.getFullYear();
you can find more at this elated.com article "working with dates"
Unfortunately your "from" dateformat is not the one which is implementation-independent in JavaScript. And all the other formats depends on the implementation, which means even if this format would be understood by most of the implementation I/you can't be sure for example how the DD and MM order would be parsed (I am almost sure it would be local regional settings dependent). So I would recommend to use a 3rd party (or your hand written) date parser to get a Date object out of your input string. One such parser you can find here:
http://www.mattkruse.com/javascript/date/
Because your question is not 100% clear for me, it's possible that you have your date in the format of /Date(number)/ which suggests that you are calling an ASP.Net service from your jQuery code. In this case during the JSON parse you can convert it to a Date object:
data = JSON.parse(data, function (key, value) {
// parsing MS serialized DateTime strings
if (key == '[NAME_OF_DATE_PROPERTY_IN_THE_JSON_STRING]') {
return new Date(parseInt(value.replace("/Date(", "").replace(")/", ""), 10));
// maybe new Date(parseInt(value.substr(6))) also works and it's simpler
}
return value;
});
The code below solved my problem:
var date = new Date(parseInt(d.data[i].dtOrderDate.replace("/Date(", "").replace(")/", ""), 10));
var day = date.getDate();
var monthIndex = date.getMonth();
var year = date.getFullYear();
Try something like this :
var date = new Date(parseInt(jsonDate.substr(6)));
where jsonDate is variable that stores your date

Difference between Date(dateString) and new Date(dateString)

I have some code that tries to parse a date string.
When I do alert(Date("2010-08-17 12:09:36"));
It properly parses the date and everything works fine but I can't call the methods associated with Date, like getMonth().
When I try:
var temp = new Date("2010-08-17 12:09:36");
alert(temp);
I get an "invalid date" error.
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Date()
With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.
new Date()
With this you're creating a new instance of Date.
You can use only the following constructors:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.
See w3schools.
EDIT: new Date(dateString) uses one of these formats:
"October 13, 1975 11:13:00"
"October 13, 1975 11:13"
"October 13, 1975"
The following format works in all browsers:
new Date("2010/08/17 12:09:36");
So, to make a yyyy-mm-dd hh:mm:ss formatted date string fully browser compatible you would have to replace dashes with slashes:
var dateString = "2010-08-17 12:09:36";
new Date(dateString.replace(/-/g, "/"));
The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.
For More Information:
Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf
I know this is old but by far the easier solution is to just use
var temp = new Date("2010-08-17T12:09:36");
Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function
function Animal(){
this.abc = 1;
return 1234;
}
var x = new Animal();
var y = Animal();
console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234
Any ideas on how to parse "2010-08-17 12:09:36" with new Date()?
Until ES5, there was no string format that browsers were required to support, though there are a number that are widely supported. However browser support is unreliable an inconsistent, e.g. some will allow out of bounds values and others wont, some support certain formats and others don't, etc.
ES5 introduced support for some ISO 8601 formats, however the OP is not compliant with ISO 8601 and not all browsers in use support it anyway.
The only reliable way is to use a small parsing function. The following parses the format in the OP and also validates the values.
/* Parse date string in format yyyy-mm-dd hh:mm:ss
** If string contains out of bounds values, an invalid date is returned
**
** #param {string} s - string to parse, e.g. "2010-08-17 12:09:36"
** treated as "local" date and time
** #returns {Date} - Date instance created from parsed string
*/
function parseDateString(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2], b[3], b[4], b[5]);
return d && d.getMonth() == b[1] && d.getHours() == b[3] &&
d.getMinutes() == b[4]? d : new Date(NaN);
}
document.write(
parseDateString('2010-08-17 12:09:36') + '<br>' + // Valid values
parseDateString('2010-08-45 12:09:36') // Out of bounds date
);
I was having the same issue using an API call which responded in ISO 8601 format.
Working in Chrome this worked:
`
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date();
var outputDate = eventDate.toDateString();
`
but this didn't work with firefox.
Above answer helped me format it correctly for firefox:
// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
var date = oDate['events']['event'][0]['start_time'];
var eventDate = new Date(date.replace(/-/g,"/");
var outputDate = eventDate.toDateString();
You can also create single Date object and update it using the static function Date.now() :
<!doctype html>
<html> <head></head>
<body>
<h1 id="datetime"></h1>
<script>
elem_datetime = document.getElementById('datetime');
var date = new Date();
function sometimer()
{
setTimeout(sometimer, 1*1000); // wait 1 second and call again
date.setTime(Date.now());
elem_datetime.innerHTML = date.toDateString() + ' ' + date.toLocaleTimeString();
}
sometimer();
</script>
</body>
</html>
You're not getting an "invalid date" error.
Rather, the value of temp is "Invalid Date".
Is your date string in a valid format?
If you're using Firefox, check Date.parse
In Firefox javascript console:
>>> Date.parse("2010-08-17 12:09:36");
NaN
>>> Date.parse("Aug 9, 1995")
807944400000
I would try a different date string format.
Zebi, are you using Internet Explorer?
I recently ran into this as well and this was a helpful post. I took the above Topera a step further and this works for me in both chrome and firefox:
var temp = new Date( Date("2010-08-17 12:09:36") );
alert(temp);
the internal call to Date() returns a string that new Date() can parse.

Categories