I am trying to determine if a string passed into a method matches the format of 'YYYYMMDD HH:MM'. I'm able to convert the string into a Carbon
date object if that helps for the verification logic. How would I best determine if the format matches my expectations?
Asked
Active
Viewed 1,548 times
0

Zach Smith
- 5,490
- 26
- 84
- 139
-
You can use `DateTime::createFromFormat()` and `DateTime::getLastErrors()`. I had written a complete answer but the question was closed before I could hit *Post*. – Álvaro González Aug 27 '20 at 14:23
1 Answers
4
You can use strtotime to convert your input to a UNIX timestamp, then create a new date string using your desired format, and compare the input to that test date string.
<?php
$dateFormat = 'Ymd h:i';
$dateInput = '20200827 10:07';
$time = strtotime($dateInput);
$testDate = date($dateFormat, $time);
if($dateInput==$testDate)
{
echo 'Valid format'.PHP_EOL;
}
else
{
echo 'Invalid format'.PHP_EOL;
}

Rob Ruchte
- 3,569
- 1
- 16
- 18
-
`DateTime::createFromFormat($dateFormat, $dateInput)->format($dateFormat) === $dateInput` is safer as it will also work with format that `strtotime` cannot parse. – KyleK Sep 03 '20 at 13:21