Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MomentJS: how to parse dates in MM/DD/YYYY & DD/MM/YYYY

How can i use moment.js in both: Australia & USA time formats?

For example:

07/08/2017 - is good for both time formats, but!

30/08/2017 - is invalid for moment.js, but i can have such dateTime

You can check it here:

http://jsfiddle.net/rLjQx/2135/

like image 337
brabertaser19 Avatar asked Jul 07 '17 16:07

brabertaser19


People also ask

How do you convert DD MM to YYYY?

First, pick the cells that contain dates, then right-click and select Format Cells. Select Custom in the Number Tab, then type 'dd-mmm-yyyy' in the Type text box, then click okay.

Is MomentJs deprecated?

MomentJs recently announced that the library is now deprecated. This is a big deal for the javascript community who actively downloads moment almost 15 million times a week.

How do I get current year in MomentJs?

year() method is used to get or set the year of the Moment object. The year value that can be set has a range from -270,000 to 270,000. Syntax: moment().


2 Answers

The parser is assuming that digits of the form XX-XX-XXXX are representing DD-MM-YYYY. If you'd like it to accept MM-DD-YYYY then you need to specify this.

eg var now2 = moment('08/30/2017', 'MM-DD-YYYY').format('MMM DD h:mm A');

You can also specify an array of different formats that you'd like it to accept so that it will recognise both:

var now2 = moment('08/30/2017', ['DD-MM-YYYY', 'MM-DD-YYYY']).format('MMM DD h:mm A');

like image 144
Billy Reilly Avatar answered Nov 08 '22 20:11

Billy Reilly


Specify the format via a second parameter to the moment call

var now2 = moment('30/08/2017', 'DD/MM/YYYY').format('MMM DD h:mm A');

Otherwise there is no way for moment to know

Related docs here: https://momentjs.com/docs/#/parsing/string-format/

Corrected fiddle: http://jsfiddle.net/wu6wwsvp/

like image 43
emd Avatar answered Nov 08 '22 20:11

emd