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".

1
  • 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. Commented Sep 24, 2020 at 19:35

1 Answer 1

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))

Sign up to request clarification or add additional context in comments.

2 Comments

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
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.