0

I'm trying to use the new Date() object in FireFox. I'm pulling the date using this code:

var createDate = document.querySelector('.formatted-absolute-date').innerText;

Which returns the following:

var createDate = document.querySelector('.formatted-absolute-date').innerText;
createDate
"2021-08-19 08:20:53 AM"

But when I try and create a new Date object using the following code, I get an Invalid Date error.

var newDate = new Date(createDate);
newDate
Invalid Date

How can I make createDate be a valid Date?

Ryan Bell
  • 169
  • 1
  • 8

2 Answers2

0

Try formatting date for new Date()

var createDate = document.querySelector('.formatted-absolute-date').innerText;
console.log(createDate)
createDate = createDate.split(" ");

var newDate = new Date(createDate[0]+"T"+createDate[1])
console.log(newDate)
<div class="formatted-absolute-date">2021-08-19 08:20:53 AM</div>
Harshit Rastogi
  • 1,996
  • 1
  • 10
  • 19
  • Note that if the date is `2021-08-19 08:20:53 PM` you convert it to `2021-08-19T08:20:53` and not `2021-08-19T20:20:53`. – 3limin4t0r Sep 03 '21 at 14:25
0

Thank you both Harshit, & 3limin4t0r by adding the if statement, I can get it to work as I need it to.

var createDate1 = document.querySelector('.formatted-absolute-date1').innerText;
var createDatePM1 = document.querySelector('.formatted-absolute-date1').innerText.substr(20, 2);
console.log(createDate1);

var newCreateDate1 = createDate1.split(' ');
var ecd1 = new Date(newCreateDate1[0]+'T'+ newCreateDate1[1]);

if (createDatePM1 == 'PM') {
  ecd1 = new Date(ecd1.valueOf() + 43200000)
}
console.log(ecd1);

var createDate2 = document.querySelector('.formatted-absolute-date2').innerText;
var createDatePM2 = document.querySelector('.formatted-absolute-date2').innerText.substr(20, 2);
console.log(createDate2);

var newCreateDate2 = createDate2.split(' ');
var ecd2 = new Date(newCreateDate2[0]+'T'+ newCreateDate2[1]);

if (createDatePM2 == 'PM') {
  ecd2 = new Date(ecd2.valueOf() + 43200000)
}
console.log(ecd2);
<div class="formatted-absolute-date1">2021-09-02 06:24:39 AM</div>
<div class="formatted-absolute-date2">2021-09-02 06:24:39 PM</div>
Ryan Bell
  • 169
  • 1
  • 8
  • 1
    Fails with '2021-09-02 12:24:39 AM" because the hour is parsed as 12, not 0. Also, `2021-09-02 06:24:39 PM` fails because the hour is parsed as 12, then 12 more hours are added. You have to parse the time separately and adjust the hour based on am/pm. Best to just split it into parts and call the Date constructor with the adjusted values. – RobG Sep 05 '21 at 06:06
  • 1
    Consider `function myParse(str) { let [Y,M,D,H,m,s,ap] = str.split(/\W/); H = H % 12 + (ap.toLowerCase() == 'am'? 0 : 12); return new Date(Y,M-1,D,H,m,s);}`. :-) – RobG Sep 05 '21 at 06:17
  • Thanks RobG. Using your method works. – Ryan Bell Sep 07 '21 at 18:48