I have a date string 13/05/2016 08:18, in order to get a date from that string I usenew Date(13/05/2016 08:18)
function but it gives an error because the function understands 13 as month not a day, what can I do to tell JavaScript that 13 is a day, not a month

- 810
- 3
- 16
- 25

- 1,527
- 3
- 14
- 20
-
Can you update your code for me? – Linh Tuan May 13 '16 at 08:47
-
Dealing with dates in JS can be extremely annyoing. I highly recommend using something like moment.js, it saved me a lot of time. (http://momentjs.com/) – Rob May 13 '16 at 08:50
-
Possible duplicate of [JavaScript date objects UK dates](http://stackoverflow.com/questions/3117262/javascript-date-objects-uk-dates) – thatOneGuy May 13 '16 at 08:50
4 Answers
what can I do to tell javascript that 13 is a day, not a month
Don't rely on JS constructor (that takes string as an argument) to parse any date format for you. You need to do it on your own
var dateStr = "13/05/2016 08:18";
var date = dateStr.split(/\s|\/|:/);
var d = new Date(date[2], date[1], date[0], date[3], date[4]);

- 66,980
- 10
- 72
- 94
-
The second parameter of Date expects a month index. By running it the way you have it returns `Mon Jun 13 2016 08:18:00 GMT+0100 (British Summer Time)`. You need to minus `1` from `date[1]` – Recnats Dec 11 '19 at 14:49
The Date() objects has a few different constructors, but not all browsers support all of them. The version that is supported by (as far as I know) all major browsers, including IE8 is 'yyyy/mm/dd 00:00:00' so in order to instantiate a valid Date that would work on all browsers you'll need something like new Date('2016/05/13 08:18:00')
.

- 6,666
- 6
- 46
- 69
-
ECMAScript specifies only a subset of ISO 8601 formats, and even they are unreliable. Far better to manually parse strings as for gurvinder372's answer. – RobG May 13 '16 at 14:58
There are some workaround but http://momentjs.com/ is really good. Its a great helper library to handle datetime.
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();

- 21,869
- 4
- 38
- 69

- 99
- 2
- 12
-
Agreed, moment.js it's really good to manipulate dates. But only if you need manipulate several dates in several ways, if not, this is a big plugin to only display a date. – Marcos Pérez Gude May 13 '16 at 08:54
-
Its not the best way but you could try this trick:
var dstring = '13/05/2016 08:18';
var nstr = dstring.split('/');
var datestring = nstr[1]+"-"+nstr[0]+"-"+nstr[2];
var d = new Date(datestring);
console.log(d);

- 575
- 7
- 12
-
You're right, it's not the best way. Having split the string into it's parts, you should call the Date constructor as for gurvinder372's answer. ;-) – RobG May 13 '16 at 15:00