最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

convert string to Date Javascript - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

Reset to default 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!

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);
发布评论

评论列表(0)

  1. 暂无评论