1

Let's say I've to convert this string into a Javascript Date object with this line:

new Date('2001-01-31 02:00:00 pm')

In Chrome it is fine. But in Firefox, it shows an Invalid Date. Why is that? I handled it manually, parsed the Hour part and added 12 hours when needed. But, is there any other way to convert this?

  • 1
    Look for [moment](https://momentjs.com/). It works everywhere and date manipulations are way easier. – Louys Patrice Bessette Mar 20 '22 at 09:22
  • 1
    "*…is there any other way to convert this?*" No. The only way to parse a string to a Date is to parse the string to a Date. – RobG Mar 20 '22 at 12:56
  • After the whole day surfing the internet, I think it's safe to use moment.js for date manipulation. Native Js functions are not very customisable. – Md. Nowshad Hasan Mar 20 '22 at 13:07

1 Answers1

-1

I think issue you are facing is to do with differences between Chromium based browsers and the Gecko based firefox. Thus they handle your string a little differently from each other. As for converting a string into a Date object, the only way I can think of is by parsing it, ie passing it into Date's constructor (as you have done).

Here is how I would solve this issue so it works in all browsers (by using the built-in methods inside the Date object).

const myDate = new Date();
myDate.setFullYear(2001);
myDate.setUTCMonth(0);
myDate.setUTCDate(31);
myDate.setUTCHours(0);
myDate.setUTCMinutes(0);
myDate.setUTCSeconds(0);
myDate.setUTCMilliseconds(0);


console.log(myDate); // 2001-01-31T02:00:00.000Z

// Now add a year:
const oldYear = myDate.getFullYear();
myDate.setFullYear(oldYear + 1);



// Results:
console.log("Expected result: year is 2002");
console.log(myDate); // Year is 2001 + 1 = 2002

Of course in your use case you may want to add hours, months or any other amount of time, so you can adapt accordingly.

Krokodil
  • 1,165
  • 5
  • 19
  • That doesn't answer the question, nor tell the OP why they're having their issue. – RobG Mar 20 '22 at 12:57
  • @RobG thank you for pointing this out, I've edited the answer to explain the issue a little better now. – Krokodil Mar 20 '22 at 13:09