0

I need to convert a date initially given as a string in the format "dd/mm/yyyy" to a valid date object but I'm running into problems. I use the moment.js library for this but when I try to convert it to a date object, it treats it internally incorrectly.

Initially I have:

var date_text = '02/01/2020 00:10'; //i.e. January 2, 2020.
var initial_date = new Date(date_text); //here js takes its default format and the problem starts.

var a = moment(initial_date,'DD/MM/YYYY');
console.log(a); //it keeps telling me that the date is February 1, 2020.

I have seen that this is often done "manually", i.e. by changing the order of the month and day. However, I find it hard to believe that a library as comprehensive and powerfull as moment.js has no way of doing this. I guess I haven't figured out how to do it.

Please, can someone help me in this regard?

What I specifically need is to pick up the date correctly (January 2nd and not February 1st) and preferably do it without having to alter the date "manually", that is, doing it only with the Date object of js and moment.js.

Thank you very much.

cooper
  • 635
  • 1
  • 8
  • 23
  • try using 'DD/MM/YYYY` instead of `DD/MM/YYYYYY` – Maverick Fabroa Mar 03 '21 at 13:16
  • @MaverickFabroa, sorry, I made a mistake while writting the question. The format in the script was correct (YYYY). I update the question. – cooper Mar 03 '21 at 13:21
  • Moment's second argument is to be used to specify the input format so that it can parse as you intend. You don't have to create a Date object to pass it on. `moment('02/01/2020 00:10', 'DD/MM/YYYY hh:mm').format('DD/MMM/YYYY')` – choz Mar 03 '21 at 13:28
  • 1
    Your problem lies in what ` new Date(date_text)` returns – Robert Mar 03 '21 at 13:41
  • As @RobertRocha says, your issue is with `new Date(date_text)`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Mar 03 '21 at 23:18

1 Answers1

2

You don't really need initial_date to format the date_text when you are using moment.js Try the below code to fix the date parse issue

var date_text = '02/01/2020 00:10'; //i.e. January 2, 2020.
var a = moment(date_text, 'DD-MM-YYYY HH:mm');
console.log(a);  // Thu Jan 02 2020 00:10:00 GMT+0530

Then format the date in your desired format

var b = a.format('DD/MM/YYYY');
console.log(b); // 02/01/2020
Beshambher Chaukhwan
  • 1,418
  • 2
  • 9
  • 13