从日期/时间字符串获取时间 [英] 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 then add/subtract time from it.
日期变量设置为date('YmdHis' ),给出(例如)2011年8月5日的20110805124000,12:40:00
The date variable is set with date('YmdHis'), giving (for example) 20110805124000 for August 5th 2011, 12:40:00
从值20110805124000(存储在变量$ fulltime)中的我需要只能以12:40的格式存储时间(因此忽略年,月,日和秒以及在小时和分钟之间加上冒号)在一个名为$ shorttime的变量中。那么我需要在那个时候添加几个小时(所以例如+3个小时会将$ shorttime变量的值更改为15:40)。我需要添加的小时数存储在一个名为$ addtime的变量中,该值可能是负数。
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?
感谢:)
推荐答案
< 5.0解决方案:
For the PHP < 5.0 solution:
<?php
$fulltime = '20110805124000';
$addtime = -5;
$time = substr($fulltime,8,2).":".substr($fulltime,10,2);
$time = date("H:i",strtotime($time) + ($addtime*3600));
echo $time;
?>
这篇关于从日期/时间字符串获取时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!