简体   繁体   中英

PHP convert time strtotime working incorrect for me

I need to convert time, use PHP strtotime function.

time have following format

$date1 = 12:10:00
$date2 = 00:10:00
echo date( 'Y:m:d h:i:s', strtotime( $date1 )); // 12:10:00
echo date( 'Y:m:d h:i:s', strtotime( $date2 )); // 12:10:00

How I can recognise is time 00:10 or 12:10

Thanks for help!

If you take a look at the date reference , a lower-case h is the 12-hour formatted hour. You need a capital H :

echo date( 'Y:m:d H:i:s', strtotime( $date1 )); // 12:10:00
echo date( 'Y:m:d H:i:s', strtotime( $date2 )); // 00:10:00

FWIW: Your time variables should be strings, with quotes.:

$date1 = "12:10:00";
$date2 = "00:10:00";

You can check difference using AM or PM or use 24 hours format cause 0 and 12 same mean for time different is it's am or pm

$date1 = '12:10:00';
$date2 = '00:10:00';
echo date( 'Y:m:d h:i:s A', strtotime( $date1 )); // 2014:04:16 12:10:00 PM
echo date( 'Y:m:d h:i:s A', strtotime( $date2 )); // 2014:04:16 12:10:00 AM 

or use capital H

echo date( 'Y:m:d H:i:s', strtotime( $date1 )); // 12:10:00
echo date( 'Y:m:d H:i:s', strtotime( $date2 )); // 00:10:00

h is "12-hour format of an hour with leading zeros, 01 through 12" .
You want H instead, which is 00 through 23. See http://php.net/date .

In the date format h is 12 hour. To differentiate you can either use G or you can add am or pm with a .

Ie

echo date( 'Y:m:d G:i:s', strtotime( $date1 ));
echo date( 'Y:m:d G:i:s', strtotime( $date2 ));

echo date( 'Y:m:d h:i:s a', strtotime( $date1 ));
echo date( 'Y:m:d h:i:s a', strtotime( $date2 ));
$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');

Use the 24 hour format!

$date1 = 12:10:00
$date2 = 00:10:00
echo date( 'Y:m:d H:i:s', strtotime( $date1 ));
echo date( 'Y:m:d H:i:s', strtotime( $date2 ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM