0

I have a String of the Format "2001-08-22 03:04:05.000."

How can I create a date object from it? I've tried Date.parse, but this causes errors.

newguy222
  • 111
  • 1
  • 11
  • Is the last . a typeo? Because that also might by why you're getting an error. – Alex Jul 26 '20 at 03:43
  • "2001-08-22 03:04:05.000." is not a format supported by ECMA-262 so parsing is implementation dependent, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Safari at least will return an invalid date. Manually parse it with a simple function, or use a library. – RobG Jul 26 '20 at 06:14

2 Answers2

-1

const newDate = new Date('2001-08-22 03:04:05.000');

console.log(newDate, typeof newDate, newDate.getMonth());

// throws an error
const newDate1 = new Date('2001-08-22 03:04:05.000.');

console.log(newDate1, typeof newDate1, newDate1.getMonth());

Just have to place the string in the Date() and you'll have access to it as an object

Date MDN

However if the 2001-08-22 03:04:05.000. <-- if that period isn't a typo then that might be why you're getting an error.

Edit: Also as the link says Date.parse() is discouraged due to browser compatibility.

kmoser
  • 8,780
  • 3
  • 24
  • 40
Alex
  • 141
  • 8
  • Trust the MDN link, parsing unsupported formats (and even some supported ones) is fraught. – RobG Jul 26 '20 at 22:28
-2
new Date('2001-08-22 03:04:05.000').getFullYear();
new Date('2001-08-22 03:04:05.000').getMonth();
new Date('2001-08-22 03:04:05.000').getDate();
new Date('2001-08-22 03:04:05.000').getHours();
new Date('2001-08-22 03:04:05.000').getMinutes();
new Date('2001-08-22 03:04:05.000').getSeconds();
  • Code–only answers aren't helpful. A good answer should explain why the OP has their issue and how your code fixes it. In Safari (and possibly other implementations), every expression in this answer returns NaN. – RobG Jul 26 '20 at 22:27
  • please explain how your code works – sonEtLumiere Aug 05 '20 at 03:27