Trying to convert a string to Javascript Date. My string:
var fullDate = this.date + " " + this.time + ":00";
gives an output: 24/12/2016 02:00:00
but trying to convert it in js Date object like:
var k = new Date(fullDate);
gives the output: Invalid Date
or even: var k = Date.parse(fullDate);
gives the output: NaN
Any help is wele.
I was following instructions from / so far
Trying to convert a string to Javascript Date. My string:
var fullDate = this.date + " " + this.time + ":00";
gives an output: 24/12/2016 02:00:00
but trying to convert it in js Date object like:
var k = new Date(fullDate);
gives the output: Invalid Date
or even: var k = Date.parse(fullDate);
gives the output: NaN
Any help is wele.
I was following instructions from http://www.datejs./ so far
Share Improve this question asked Dec 13, 2016 at 14:08 GeorgiosGeorgios 1,4836 gold badges17 silver badges35 bronze badges 3- 1 Your date/time format is probably not matching your locale's format, and is not ISO... it should be either of those. – daniel.gindi Commented Dec 13, 2016 at 14:10
- I don't know what the guidance on datejs. says, but try reading some reliable documentation on this (e.g. developer.mozilla/en/docs/Web/JavaScript/Reference/…) and checking what date formats are understood by the date constructor, it's not actually that many. Other libraries like MomentJS can parse dates in a wider variety of formats. – ADyson Commented Dec 13, 2016 at 14:13
- This is a good summary for this issue actually: stackoverflow./questions/3257460/… – ADyson Commented Dec 13, 2016 at 14:15
3 Answers
Reset to default 5Your format is invalid. Valid format is month/day/year
, so try:
var fullDate = "12/24/2016 02:00:00";
var k = new Date(fullDate);
Hope I could help!
I've just posted an answer/question for this. Here's my answer
In summary you need to format the string to a standardized format first and then you can use that string with the new Date(string) method. This work for many browsers (IE9+, Chrome and Firefox).
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
That's happening because you don't provide a valid date format for the new Date
. So the date format is incorrect. The default date format in JavaScript is dd/mm/yyyy
.
The date should be like(mm/dd/yyyy
):
12/24/2015
And then you can use var k = new Date(fullDate);
A pure javascript solution to format the date(without moment.js
):
var fullDate = "24/12/2016 02:00:00";
fullDate = fullDate.split(' ');
var date = fullDate[0].split(/\//);
var time = fullDate[1];
var newDate = date[1] + '/' + date[0] + '/' + date[2] + ' ' + time;
var k = new Date(newDate);