1

I want to check the date input and convert it to 24h format. For example the datetime is:

$date="2021-02-5 11:45:00 AM"

and after i check it with this condition:

 if (preg_match("/am|pm|AM|PM/", $date))
        {
            $date=date('Y-m-d H:i:s',strtotime("$date"));
        }

and my output should be like this however it does not return a date format like that:

$date="2021-02-5 11:45:00";

How can i fix this problem?

msanli224
  • 41
  • 1
  • 9
  • When you say "doesn't work", is it because you get `05` rather than `5`? What's what you're asking with `d`. Format codes are documented [here](https://www.php.net/manual/en/datetime.format.php#refsect1-datetime.format-parameters). – Álvaro González Feb 05 '21 at 08:58
  • `"$date"` is equivalent to `$date`. – KIKO Software Feb 05 '21 at 09:01
  • 1
    do you receive the same date format all the time ? The best way to deal with dates in php is to use the internal functions, such as DateTime object which allow you to createFromFormat and then format method to transform it, i can show you an example if you want in an answer – Snroki Feb 05 '21 at 09:04

4 Answers4

1

Converting time format

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));
Mohit Chandel
  • 1,838
  • 10
  • 31
0
date_create_from_format('Y-m-j H:i:s A', $date);

It will return a DateTime object, and you can get right date you want, and it will return false if date string don't match the pattern.

DateTime Object
(
    [date] => 2021-02-05 11:45:00.000000
    [timezone_type] => 3
    [timezone] => UTC
)
date_create_from_format ( string $format , string $time , DateTimeZone $timezone = ? ) : DateTime
Goo
  • 68
  • 9
0

You don't need regex to check if it is 24 hours or 12 hours. you can simply pass the date to strtotime function to get a timestamp of the date and then format the timestamp with date function.

$date="2021-02-5 11:45:00 AM";
$date=date('Y-m-j H:i:s',strtotime($date));
echo $date;  // 2021-02-5 11:45:00
Amir Sasani
  • 317
  • 6
  • 19
0

With strtotime you have no control over the formats. To be on top of what is happening better use the feature-rich DateTime class. First convert the string to a DateTime object and then format it to whatever you need.

<?php
$dt = "2021-02-5 11:45:00 pm";

if (preg_match('/am$|pm$/i', $dt)) // is there an Ante meridiem/Post meridiem suffix?
{
    $dtFormat = 'Y-n-j H:i:s a';
}
else 
{
    $dtFormat = 'Y-n-j H:i:s';
}

$ts = DateTime::createFromFormat($dtFormat, $dt);
$date = $ts -> format('Y-m-d H:i:s');

// echo 'Result: '. $date;
Stefanov.sm
  • 11,215
  • 2
  • 21
  • 21