6

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 welcome.

I was following instructions from http://www.datejs.com/ so far

3
  • 1
    Your date/time format is probably not matching your locale's format, and is not ISO... it should be either of those. Commented Dec 13, 2016 at 14:10
  • I don't know what the guidance on datejs.com says, but try reading some reliable documentation on this (e.g. developer.mozilla.org/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. Commented Dec 13, 2016 at 14:13
  • This is a good summary for this issue actually: stackoverflow.com/questions/3257460/… Commented Dec 13, 2016 at 14:15

3 Answers 3

5

Your 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!

Sign up to request clarification or add additional context in comments.

1 Comment

if the string contains miniseconds,how to convert?
4

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.