Need to validate MM/dd/yyyy hh:mm tt in Javascript

前端 未结 3 833
悲哀的现实
悲哀的现实 2021-01-28 13:19

I need to validate a date string in a specific format in Javascript.

The format is: MM/dd/yyyy hh:mm tt

I\'m having a really hard time trying to find either a da

相关标签:
3条回答
  • 2021-01-28 14:04

    A stricter regex:

    /[01]\d\/[0-3]\d\/\d{4} [01]\d:[0-5]\d [AP]M/
    
    0 讨论(0)
  • 2021-01-28 14:06

    Do you need to validate that it is an actual date, or just that it follows that exact format? If just the format, you can use this regex:

    /[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [aApP][mM]/
    

    You could use Date.js in combination with the above regex to validate that it is a valid date, and matches your exact format. Examples:

    01/01/9999 01:00 AM - matches
    12/31/9999 01:59 PM - matches
    99/99/9999 99:99 AM - no match (day/month out of range)
    12/31/9999 99:59 PM - no match (hours out of range)
    01/01/9999 99:99 A  - no match (no match on A)
    

    Full JS example:

    var re = /[0-1]\d\/[0-3]\d\/\d{4} [0-1]\d:[0-5]\d [AP][M]/; // [aApP][mM] for case insensitive AM/PM
    var date = '10/21/2011 06:00 AM';
    if (re.test(date) && date.parseExact(date, ['MM/dd/yyyy hh:mm tt']){
        // date is exact format and valid
    }
    
    0 讨论(0)
  • 2021-01-28 14:12

    Try this regular expression for the format dd/MM/yyyy hh:mm tt

    "[0-3][0-9]\/[0-1][0-9]\/[0-9]{4} [0-1][0-9]:[0-5][0-9] [paPA][Mm]" 
    

    the above expression works as the below formats

    01/12/9999 01:00 AM - matches
    12/31/9999 01:59 PM - no match
    39/19/9999 01:59 PM - matches
    39/19/9999 99:99 PM - no match (time out of range)
    12/31/9999 99:59 PM - no match (hours out of range)
    
    0 讨论(0)
提交回复
热议问题