This question already has an answer here:
I have a time as 5:4 pm
and i want convert the time from AM/PM to 24 hour format in PHP, i try as date('H:i',strtotime('5:4 pm'))
but this don't work and result is 16:00
in the event that it should be 17:04
. what do i do?
DEMO: http://sandbox.onlinephpfunctions.com/code/bfd524f65ea4fa3031e55c9879aab711f31e1b37
I can not change this time.
</div>
Assuming the time string format will be same -
$time = explode(' ', '5:4 pm');
$temp = date_parse($time[0]);
$temp['minute'] = str_pad($temp['minute'], 2, '0', STR_PAD_LEFT);
echo date('H:i a', strtotime($temp['hour'] . ':' . $temp['minute'] . ' ' . $time[1]));
Output
17:04 pm
Try to capitalize AM/PM
date('H:i', strtotime('5:04 PM'))
{EDIT}
Replace pm with PM using str_replace
echo date('H:i', strtotime(str_replace("pm","PM",'5:04 PM')))
You should pass 5:04 pm instead of 5:4 pm, it seems the parameter expects 2 digits for the minute format.
Working example: http://sandbox.onlinephpfunctions.com/code/ecf968c844da50e8a9eec2dc85656f49d7d20dee
You can try this
echo date("H:i", strtotime("05:04 PM"));
I recommend PHP OOP way as they are always better than any procedural way(like using strtotime
):
$time = '5:04 pm';
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');//17:04
Please mind that you need to provide : 5:04 pm , you CAN NOT use 5:4 pm .
Reason is that no date format exist for minutes without a leading zero.
For reference see this: http://php.net/manual/en/datetime.createfromformat.php
If you have to have time in that format then you will need to manipulate it after you receive your time as follows:
$time = '5:4 pm';//works for formats -> '5:4 pm' gives 17:04,'5:40 pm' gives 17:40
$time2 = str_replace(' ',':',$time);
$time3 = explode(':',$time2);
if(((int)$time3[1])<10)//check if minutes as over 10 or under 10 and change $time accordingly
$time = $time3[0].':0'.$time3[1].' '.$time3[2];
else
$time = $time3[0].':'.$time3[1].' '.$time3[2];
$date = DateTime::createFromFormat('g:i a', $time);
echo $date->format('H:i');
I hope it helps
Here is the code,
$time = '5:4 pm';
$arr = explode(" ",$time);
$arr1 = explode(":",$arr[0]);
foreach($arr1 as $k => $val){
$arr1[$k] = sprintf("%02d", $val);
}
$str = implode(":", $arr1)." ".$arr[1];
echo date('H:i',strtotime($str));
pure date wont work, so I am exploding it as it is special case
I hope this will work. Thanks :)
// 24 hours format
$date = date("H:i a",time());
// just pass time() function instead of strtotime()
echo $date;
// output
// 17:04 pm
// to run a test, do reset your system time back or forward to 5:4 pm
Thanks, hope this helps.