开发者

Get time from a date/time string

I have a date value stored in a variable. I need to extract the time part of the value in to a separate variable and th开发者_StackOverflow中文版en add/subtract time from it.

The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00

From the value 20110805124000 (which is stored in the variable $fulltime), I need to store the time only in the format 12:40 (so ignoring the year, month, day and seconds and adding the colon between the hour and minute) in a variable called $shorttime. I then need to add a number of hours to that time (so for example +3 hours would change the value in the $shorttime variable to 15:40). The number of hours I need to add is stored in a variable called $addtime, and this value could be a negative number.

Is this easily doable? Could anyone help?

Thanks :)


$time = '2013-01-22 10:45:45';

echo $time = date("H:i:s",strtotime($time));

It will give the time 10:45:45 from datetime.


<?PHP

$addhours = 3;

$date = DateTime::createFromFormat('YmdHis', '20110805124000');
$shorttime = $date->format("H:i");
$newdate = $date->add(DateInterval::createFromDateString($addhours . "hours"));
$newtime = $newdate->format("H:i");


echo $shorttime . "<br />";
echo $newtime . "<br />";
?>

for your reference:

http://www.php.net/manual/en/datetime.createfromformat.php

http://www.php.net/manual/en/dateinterval.createfromdatestring.php


hello the way I usually do it is like this, maybe it's a bit long but it works for me...

            $DateIn  = new DateTime($In);
            $DateOut = new DateTime($Out);
            $HourOut = new DateTime($H_Out);   
            
            $FechaEntrada = $DateIn->format('d-m-Y');
            $FechaSalida  = $DateOut->format('d-m-Y');
            $HoraSalida   = $HourOut->format('H:i a');

the guide I used was the PHP one DateTime::format()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜