Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying Date/Time Input in PHP

New to programming in PHP. Trying to verify input format for a date/time. User input is as follows for Nov 27 2012 at 6 PM '2012-nov-27|6pm'.

Not really sure where to start. Any suggestions? Thanks.

like image 216
progmtb Avatar asked Mar 10 '26 04:03

progmtb


2 Answers

Have a look here for date_parse_from_format documentation and here for general date formatting. Give this a try:

<?php
$date = "2012-nov-27|6pm";
print_r(date_parse_from_format("Y-M-d|ga", $date));
?>
like image 75
Tim S Avatar answered Mar 12 '26 17:03

Tim S


Gangnam OOP style:

$input = '2012-nov-27|6pm';
$date  = \DateTime::createFromFormat('Y-M-j ga', str_replace('|', ' ', $input));
if ($date === false) {
    throw new \Exception('Invalid date!');
}

NOTE: I experienced an issue by using | in format/date string, so that the str_replace()

NOTE 2: If input day format is 01-31 instead of 1-31, replace the j with a d in createFromFormat() first parameter.

like image 45
Carlos Avatar answered Mar 12 '26 19:03

Carlos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!