1

I have a string like "August 24th, 2020" that I need to convert into the "Date" type in Angular. Is there any simple way to do this please?

I've tried this:

const deadline = new Date ("August 24th, 2020")

But that results in "Invalid Date".

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • You shouldn't rely on `Date()` parser as it is strongly discouraged, especially for such tough cases. Check out my answer below for possible approach. – Yevhen Horbunkov Sep 24 '20 at 19:35

1 Answers1

2

Maybe moment.js is capable to parse that outside of the box, however, if you're not willing to attach external library and maintain its compatibility to the rest of your environment for this purpose only, you may parse that yourself:

const dateStr = "August 24th, 2020",

      parseDate = s => {
        const [, month, dd, yyyy] = s.match(/([a-z]+)\s(\d+)[a-z]+,\s(\d+)/i)||[],
              months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
        return new Date(Date.UTC(yyyy, months.indexOf(month), dd))
      }
      
console.log(parseDate(dateStr))
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
  • I sometimes get an error saying "object null is not iterable (cannot read property Symbol(Symbol.iterator)) at parseDate (job-feed.service.ts:155)" which I don't get – Randy Quaye Sep 24 '20 at 21:04
  • @RandyQuaye : that may happen, when you pass the string date, formatted differently (e.g. `'25/09/2020'` instead of `'September 25th, 2020'`). I have applied slight tweak in the latest edit to return `Invalid Date` when input string format is different. – Yevhen Horbunkov Sep 25 '20 at 07:25