Search code examples
javascriptangulartypescriptangular-date-format

Convert custom string into Angular Date


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


Solution

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