Reputation: 449
I have datetime 30-12-1899 9:25:52 AM
here needed only time that is 9:25:52 AM
.this time i wanted to insert in mysql
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.
Upvotes: 12
Views: 31641
Reputation: 22741
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");
Upvotes: 2
Reputation: 43582
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
Upvotes: 1
Reputation: 3487
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);
?>
Upvotes: 5
Reputation: 3170
$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
Upvotes: 12
Reputation: 2622
This can be alternative
<?php
$date = "30-12-1899 9:25:52 AM";
$date = explode(' ',$date);
echo date[1].' '.date[2];
?>
Upvotes: 0
Reputation: 28773
You can try with explode
like
$date = "30-12-1899 9:25:52 AM";
$date_arr = explode(' ',$date);
echo $date_arr[1];
Upvotes: 0
Reputation: 68556
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";
Upvotes: 12