-2

When page is loaded, my input box gets automatically populated with a date time. This date time can be in any valid format like DD-MMM-YYYY - HH:mm, MMM DD, YYYY - HH:mm, etc and I wanted to pick up this date, parse it and add some hours to it.
But when I try to parse a date which is something like 19-02-2020 - 00:00 (DD-MM-YYYY - HH:mm), it gives me an invalid Date. I have tried

new Date('19-02-2020 - 23:00')
// output - Invalid Date

and also tried using moment JS to format the date like

moment("19-02-2021 - 23:00","DD-MM-YYYY - HH:mm").toDate();
// output - Fri Feb 19 2021 23:00:00 GMT+0530 (India Standard Time)

but now all the other dates will be parsed wrong like this one

moment("19-02-2021 - 23:00","DD-MMM-YYYY - HH:mm").toDate();
// output - Tue Jan 19 2021 23:00:00 GMT+0530 (India Standard Time)

Is there a correct and reliable way to do this?

  • *can be in any valid format* - well you need to know what format it is to correctly parse it. What if I enter `-895-8-FSSsd-#8893` and claim it's my secret encoded date format? – T J May 03 '21 at 15:58
  • 3
    why did you use `-MMM-` on the second example? – TKoL May 03 '21 at 15:59
  • 1
    Also, what process is 'automatically populating' the input box? if you had some clarity on that, it would make your job easier. – TKoL May 03 '21 at 15:59
  • It is guaranteed that the format will be valid. Do I have to handle all formats differently ? or is there a universal way to parse any format ? – Sarthak Sharma May 03 '21 at 16:00
  • @TKoL `-MMM-` is also part of a valid date format but I did not get the correct result s while using moment JS – Sarthak Sharma May 03 '21 at 16:01
  • @TKoL that's a script that runs on page load and populates the input box. – Sarthak Sharma May 03 '21 at 16:03
  • @SarthakSharma of course you didn't get the correct result, the date you passed to it is in `-MM-` format, not `-MMM-`. So what does the code look like in that script that runs on page load? How is it populating that field? What date format is it using? – TKoL May 03 '21 at 16:04
  • 1
    It just seems odd that you have a script that 'automatically inputs a date' but you can't say anything more specific about that date other than 'its a valid format'. Why does the script not use the same format every time? – TKoL May 03 '21 at 16:06
  • @TKoL The format of the date is config-driven and can change anytime. But I would know what format was being used to populate the date so that I can parse it again – Sarthak Sharma May 03 '21 at 16:22

2 Answers2

0

Date constructor accepts ISO 8601 and RFC 2822 date/time formats:

let dates = [
  new Date('2020-02-19T23:00Z'),
  new Date('2020-02-19 23:00Z'),
  new Date('Wed Feb 19 2020 23:00:00 UTC'),
]
console.log(dates)

When your date/time information has fixed nonstandard format, you can use regular expressions to convert it to RFC 3339 format and then parse it:

let rfc3339 = "19-02-2020 - 00:00".replace(/(\d*)-(\d*)-(\d*) - (\d*):(\d*)/, (_, d, m, y, h, min) => `${y}-${m}-${d}T${h}:${min}Z`);
let date = new Date(rfc3339);
console.log(date)

You can combine this into one function:

function parseDate(dateStr) {
  const re = /(\d\d)(, |-)(\d\d)\2(\d\d\d\d) - (\d\d):(\d\d)/;

  let groups = re.exec(dateStr);

  if (groups == null) {
    return null; // on invalid input
  }

  let rfc3339Str;
  if (groups[2] == '-') {
    rfc3339Str = `${groups[4]}-${groups[3]}-${groups[1]}T${groups[5]}:${groups[6]}Z`;
  } else {
    rfc3339Str = `${groups[4]}-${groups[1]}-${groups[3]}T${groups[5]}:${groups[6]}Z`;
  }

  let date = new Date(rfc3339Str);
  return date;
}

for (dateStr of [
    '04, 23, 2020 - 12:34',
    '23-04-2020 - 12:34',
  ]) {
  console.log(parseDate(dateStr));
}
jiwopene
  • 3,077
  • 17
  • 30
  • Dates constructor gives me invalid date for `new Date("19-02-2021 - 23:22")`. How to parse when my date String is `"19-02-2021 - 23:22"` – Sarthak Sharma May 03 '21 at 16:29
  • You'll need probably custom parsing routine. Wait a moment, I'll add it to the answer. – jiwopene May 03 '21 at 16:57
  • The second example format is not supported by ECMA-262 and produces an invalid Date in some implementations. – RobG May 03 '21 at 20:40
0

the Date string format is YYYY-MM-DDTHH:mm:ss.sssZ where T is a delimiter and Z reffer to the timezone (optional).

HH:mm:ss.sss is equivalent to: hours, minutes, seconds ,and milliseconds.

const date = new Date( Date.parse('2021-02-19T00:05:00.000') );
console.log(date)

Learn more about Date object: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

charmful0x
  • 155
  • 9