Asked  7 Months ago    Answers:  5   Viewed   29 times

Below is how I previously verified dates. I also had my own functions to convert date formats, however, now am using PHP's DateTime class so no longer need them. How should I best verify a valid date using DataTime? Please also let me know whether you think I should be using DataTime in the first place. Thanks

PS. I am using Object oriented style, and not Procedural style.

static public function verifyDate($date)
{
  //Given m/d/Y and returns date if valid, else NULL.
  $d=explode('/',$date);
  return ((isset($d[0])&&isset($d[1])&&isset($d[2]))?(checkdate($d[0],$d[1],$d[2])?$date:NULL):NULL);
}

 Answers

49

You can try this one:

static public function verifyDate($date)
{
    return (DateTime::createFromFormat('m/d/Y', $date) !== false);
}

This outputs true/false. You could return DateTime object directly:

static public function verifyDate($date)
{
    return DateTime::createFromFormat('m/d/Y', $date);
}

Then you get back a DateTime object or false on failure.

UPDATE:

Thanks to Elvis Ciotti who showed that createFromFormat accepts invalid dates like 45/45/2014. More information on that: https://stackoverflow.com/a/10120725/1948627

I've extended the method with a strict check option:

static public function verifyDate($date, $strict = true)
{
    $dateTime = DateTime::createFromFormat('m/d/Y', $date);
    if ($strict) {
        $errors = DateTime::getLastErrors();
        if (!empty($errors['warning_count'])) {
            return false;
        }
    }
    return $dateTime !== false;
}
Wednesday, March 31, 2021
 
samayo
answered 7 Months ago
72

Try this:

$tZone = new DateTimeZone("Europe/Amsterdam");
Saturday, May 29, 2021
 
mnagel
answered 5 Months ago
41

I'm not sure what format you're looking for in your difference but here's how to do it using DateTime

$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
Friday, June 4, 2021
 
Jesse
answered 5 Months ago
50

You don't need the date validator. It doesn't support dd/mm/yyyy format, and that's why you are getting "Please enter a valid date" message for input like 13/01/2014. You already have the dateITA validator, which uses dd/mm/yyyy format as you need.

Just like the date validator, your code for dateGreaterThan and dateLessThan calls new Date for input string and has the same issue parsing dates. You can use a function like this to parse the date:

function parseDMY(value) {
    var date = value.split("/");
    var d = parseInt(date[0], 10),
        m = parseInt(date[1], 10),
        y = parseInt(date[2], 10);
    return new Date(y, m - 1, d);
}
Tuesday, August 10, 2021
 
braindamage
answered 3 Months ago
24

You could use the TryParseExact method which allows you to pass a collection of possible formats that you want to support. The TryParse method is culture dependent so be very careful if you decide to use it.

So for example:

DateTime fromDateValue;
string s = "15/07/2012";
var formats = new[] { "dd/MM/yyyy", "yyyy-MM-dd" };
if (DateTime.TryParseExact(s, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromDateValue))
{
    // do for valid date
}
else
{
    // do for invalid date
}
Thursday, August 12, 2021
 
Zword
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :