从日期/时间字符串获取时间

2022-08-30 16:20:09

我有一个日期值存储在变量中。我需要将值的时间部分提取到一个单独的变量中,然后从中加/减时间。

date 变量使用 date('YmdHis') 进行设置,例如,给出 2011 年 8 月 5 日 12:40:00 的20110805124000

从值20110805124000(存储在变量$fulltime中),我只需要将时间存储在一个名为$shorttime的变量中,格式为12:40(因此忽略年,月,日和秒,并在小时和分钟之间添加冒号)。然后,我需要在该时间上添加一些小时数(例如,+3小时会将$shorttime变量中的值更改为15:40)。我需要添加的小时数存储在一个名为 $addtime 的变量中,此值可以是负数。

这很容易做到吗?任何人都可以帮忙吗?

谢谢:)


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

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

它将从日期时间开始提供时间。10:45:45


答案 2
<?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 />";
?>

供您参考:

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

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


推荐