How to get time from datetime
Solution 1
Do the OOP way
<?php
$date1="30-12-1899 9:25:52 AM";
$format = 'd-m-Y H:i:s A';
$date = DateTime::createFromFormat($format, $date1);
echo $date->format('H:i:s A') . "\n";
Solution 2
$s = '30-12-1899 9:25:52 AM';
$dt = new DateTime($s);
$date = $dt->format('d-m-Y');
$time = $dt->format('h:i:s A');
echo $time;
see details here http://docs.php.net/class.datetime
Solution 3
actually the code does exactly what you want
<?php
$date = "30-12-1899 9:25:52 AM";
$date = strtotime($date);
echo date('H:i:s', $date);
?>
Solution 4
Can you try this,
$date = "1899-12-30 9:25:52 AM";
echo $start_time = date("h:i:s A", strtotime($date));
OR
$date = "30-12-1899 9:25:52 AM";
$dtime = new DateTime($date);
echo $dtime->format("h:i:s A");
Solution 5
You get 01:00:00
as result, because on your version of PHP, strtotime()
function returns invalid integer. More likely value false
is returned, and when you format false
via date()
function, you will get 1970-01-01 00:00:00
. You get time 01:00:00
because you have timezone offset, you are probably in UTC+1
timezone.
Here you can see, that your code will not work correctly on PHP version bellow 5.2.6
, even on x64 machines, and results will be unreliable.
Best option would be to upgrade your PHP version (or change webhosting). But if you do not have this options, you can use string functions to break and concatenate date & time parts, like this:
$date = "30-12-1899 9:25:52 AM";
sscanf($date, "%d-%d-%d %d:%d:%d %s", $d, $m, $Y, $g, $i, $s, $A);
$h = $A == 'AM' ? $g : $g + 12;
echo "$Y-$m-$d $h:$i:$s"; # 1899-12-30 9:25:52
echo "$h:$i:$s"; # 9:25:52
snehal
Updated on July 28, 2022Comments
-
snehal almost 2 years
I have datetime
30-12-1899 9:25:52 AM
here needed only time that is9:25:52 AM
.this time i wanted to insert inmysql
database and this field has data type time.my code is :
<?php $date = "30-12-1899 9:25:52 AM"; $date = strtotime($date); echo date('H:i:s', $date); ?>
when execute it returns:
01:00:00
i am not getting where is the problem.Can any one help me on this.
thank you.