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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6955838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:40:56  来源:igfitidea点击:

Get time from a date/time string

phpdatetime

提问by Ross

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 then add/subtract time from it.

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

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

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

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.

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

Is this easily doable? Could anyone help?

这容易实现吗?有人可以帮忙吗?

Thanks :)

谢谢 :)

回答by Bindiya Patoliya

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

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

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

它将给出10:45:45日期时间的时间。

回答by Saad Imran.

<?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/datetime.createfromformat.php

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

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