digitup
digitup

Reputation: 537

Convert a String to JS Date

I am trying to convert a string value into a JavaScript Date format but I don't seem to find a simple way to do it without having to use additional library such as datejs

var dateString = "20131120";
    var date       = new Date(dateString);
console.log(date);
     // I need to add an additional day to the original string
    var newDate    = date.getFullYear() + '-' + (date.getMonth()+1) + '-' + (date.getDate()+1);
console.log(newDate);

Any hints are much appreciated.

Upvotes: 0

Views: 101

Answers (4)

BhavikKama
BhavikKama

Reputation: 8800

Can you please try this code

 var dateString  = "20131120";
    var year        = dateString.substring(0,4);
    var month       = dateString.substring(4,6);
    var day         = dateString.substring(6,8);
    var date        = new Date(year, month-1, day);

Here just used the simple substring method

First (0,4) will extract the year then next two is for month and next two is for day of month

  NOTE:
    Here we doing  `month-1` because it will count from 0 e.g (january==0).

hope it helps

Upvotes: 5

epascarello
epascarello

Reputation: 207537

Simple reg expression:

new Date("20131120".replace(/(\d{4})(\d{2})(\d{2})/,"$2/$3/$1"))

It is very basic regular expression.

Match 4 numbers, Match 2 numbers, Match 2 numbers in groups.

The replace works by using the groups $1 is the first match, $2 is the second match, $3 is the third match. Learn about regular expressions.

Upvotes: 3

RobG
RobG

Reputation: 147503

Before ES5, parsing of date strings was entirely implementation dependent. Now a version of ISO8601 has been specified, but it isn't supported by all browsers in use. So the best way is to manually parse it.

So in this case I'd do:

var dateString = "20131120";
var m = dateString.match(/\d\d/g);
var date = new Date(m[0] + m[1], --m[2], m[3]);

which will work in any browser in use that supports javascript.

Upvotes: 2

Sagar Rawal
Sagar Rawal

Reputation: 1442

The best you can do is use the ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS

For example: new Date('2011-04-11')

or

new Date('2011-04-11T11:51:00')

For more Info: MDN | Date

For old Internet Explorer compatibility (IE versions less than 9 do not support ISO format in Date constructor), you should split datetime string representation to it's parts and then you can use constructor using datetime parts, e.g.: new Date('2011', '04' - 1, '11', '11', '51', '00')

Note that the number of the month must be 1 less.

Upvotes: -2

Related Questions