0

I have this date in string format:

"05/2016" or "12/2015"

How can I convert the dates above in string format to Date() javascript object?

Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
Michael
  • 13,950
  • 57
  • 145
  • 288

4 Answers4

4

Date constructor accepts params in next order: year, month, day, hours, minutes, seconds, milliseconds, so simply parse string and pass it into Date constructor.

var data = "05/2016".split('/');
// Add + before year to convert str into number. Decrease second param because month starts from 0..11. 
var date = new Date(+data[1],data[0]  - 1);
console.log(date);

Also, you can convert your string to format which would be parsed correctly by new Date ( See more about dateString in MDN Date.parse description.

// convert string "05/2016" -> "2016-05"
var dateString = "05/2016".split('/').reverse().join('-');
var date = new Date(dateString);
console.log(date);
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82
2

The previous answers are not correct - they get either the month or the year wrong. This is right (see the comment by Frédéric Hamidi)

var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10)-1)
console.log(date)
Chris Lear
  • 6,592
  • 1
  • 18
  • 26
  • My guess it's ugly to blame others answers as they aren't constants and can be easily updated. Also consider adding own comment to help author fix problem instead of partially duplicating others code (as result buggy answer would be kept , sure I mean simple cases as in that SO question ... ) – Andriy Ivaneyko Jun 06 '16 at 08:33
1

You can split string to get an array then use Date constructor.

new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);

var str = "12/2015";
var arr = str.split('/');
var date = new Date(parseInt(arr[1], 10), parseInt(arr[0], 10) - 1)
console.log(date)
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

You might want to look at Converting string to date in js

I had a similar issue and stumbled upon this existing link.

Community
  • 1
  • 1
whyAto8
  • 1,660
  • 4
  • 30
  • 56