Reputation: 978
Im giving date as a string and then trying to convert it to ISO.
Here is what I have been doing:
var dateValue = "Tue Sep 29 2015 16:50:00 GMT+0530 (IST)"
alert(dateValue.toISOString());
But this is returning me the following error "toISOString is not a function"
Why is this?
Upvotes: 0
Views: 2633
Reputation: 1074168
Why is this?
Becase your dateValue
is a string, and toISOString
isn't a method on strings (it is on dates).
To use it, you'll need a Date
object. There's no guarantee in the specification that the format you've shown will be successfully parsed by anything built into JavaScript, so you'll need to parse it with something that does make that guarantee: Either your own code, or a library like MomentJS.
The format in question is quite easy to parse if it's stable:
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
};
var dateValue = "Tue Sep 29 2015 16:50:00 GMT+0530 (IST)";
var rex = /^.{4}(.{3}) (\d{2}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT([+-]\d{4})/;
var data = dateValue.match(rex);
snippet.log("Day: " + data[2]);
snippet.log("Month: " + months[data[1].toLowerCase()]);
snippet.log("Year: " + data[3]);
snippet.log("Hour: " + data[4]);
snippet.log("Minute: " + data[5]);
snippet.log("Second: " + data[6]);
snippet.log("Offset: " + data[7]);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
...then just use the new Date(year, month, ...)
constructor to create the date, and adjust the time based on the offset (be sure to use the UTC methods on Date
).
Upvotes: 4