2

Is there any way to test the date formats.

I have tried below method

let newdate = new Date(myStringDate); Date.parse(myStringDate) result = `${newdate.getDate()}/${newdate.getMonth() + 1}/${newdate.getFullYear()}` 

Here i will get result in dd/MM/yyyy format. And now i need to check the format is valid or not. Please look into this and provide me a suitable way to check the format.

2 Answers 2

2

provide me a suitable way to check the format.

Here is an example using moment:

export namespace Dates { export const dateFormats = { dateTimeFormat: 'DD/MM/YYYY HH:mm', dateOnlyFormat: 'DD/MM/YYYY', monthYearFormat: 'MM/YYYY', isoFormat: 'YYYY-MM-DD HH:mm:SS ', // Corresponds to '2016-01-04T13:00:00Z' } export function toDate(value: string, /** * The default has *all* the formats * - This is because strict date type validations * - are done by passing in explicit limited sets. **/ formats = [ dateFormats.dateTimeFormat, dateFormats.dateOnlyFormat, dateFormats.isoFormat, dateFormats.monthYearFormat, ] ): { valid: boolean, date: Date | null } { if (!value || !value.trim().length) { return { valid: true, date: null }; } let trimmed = value.trim(); if (!formats.some(format => format.length == trimmed.length)) { return { valid: false, date: null }; } // http://momentjs.com/docs/#/parsing/string-formats/ let date = moment(value, formats, true); if (!date.isValid()) { return { valid: false, date: null }; } return { valid: true, date: date.toDate() }; } } 

Feel free to change the date formats as needed 🌹

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

Comments

0

The cheapest way to implement is to use a regular expression to check the returned format

Here is the regular expression

var pattern = new RegExp('^((([1-2][0-9])|(3[0-1]))|([1-9]))/((1[0-2])|([1-9]))/[0-9]{4}$'); 

The above pattern will check for following formats

  • 1/1/1991
  • 1/12/1991
  • 30/1/1991
  • 30/12/1991

Added bonus The regular expression can also check for incorrect dates like having 32 as a date or 0 in the month and even month greater than 12.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.