Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string is a legal "dd/mm/yyyy" date?

Given a string str, how could I check if it is in the dd/mm/yyyy format and contains a legal date ?

Some examples:

bla bla      // false
14/09/2011   //         true
09/14/2011   // false
14/9/2011    // false
1/09/2011    // false
14/09/11     // false
14.09.2011   // false
14/00/2011   // false
29/02/2011   // false
14/09/9999   //         true
like image 456
Misha Moroshko Avatar asked Sep 28 '11 11:09

Misha Moroshko


People also ask

How do I check if a string is in format dd mm yyyy?

parseExact so you can just do Date. parseExact(dateString,"dd/MM/yyyy") .

Should I use mm/dd/yyyy or MM YYYY?

The United States is one of the few countries that use “mm-dd-yyyy” as their date format–which is very very unique! The day is written first and the year last in most countries (dd-mm-yyyy) and some nations, such as Iran, Korea, and China, write the year first and the day last (yyyy-mm-dd).

How do you check if the date is in dd mm yyyy format in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019"));


Video Answer


1 Answers

Edit: exact solution below

You could do something like this, but with a more accurate algorithm for day validation:

function testDate(str) {
  var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if(t === null)
    return false;
  var d = +t[1], m = +t[2], y = +t[3];

  // Below should be a more acurate algorithm
  if(m >= 1 && m <= 12 && d >= 1 && d <= 31) {
    return true;  
  }

  return false;
}

http://jsfiddle.net/aMWtj/

Date validation alg.: http://www.eee.hiflyers.co.uk/ProgPrac/DateValidation-algorithm.pdf

Exact solution: function that returns a parsed date or null, depending exactly on your requirements.

function parseDate(str) {
  var t = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
  if(t !== null){
    var d = +t[1], m = +t[2], y = +t[3];
    var date = new Date(y, m - 1, d);
    if(date.getFullYear() === y && date.getMonth() === m - 1) {
      return date;   
    }
  }

  return null;
}

http://jsfiddle.net/aMWtj/2/

In case you need the function to return true/false and for a yyyy/mm/dd format

function IsValidDate(pText) {
    var isValid = false ;
    var t = pText.match(/^(\d{4})\/(\d{2})\/(\d{2})$/);

    if (t !== null) {
        var y = +t[1], m = +t[2], d = +t[3];
        var date = new Date(y, m - 1, d);

        isValid = (date.getFullYear() === y && date.getMonth() === m - 1) ;
    }

    return isValid ;
}
like image 66
Adam Jurczyk Avatar answered Oct 13 '22 00:10

Adam Jurczyk