好时光
我有一个像2017-05-11 22:35:45
这样的文本时间,我想在这个时间上加上 24 小时并计算剩余时间。
E.x:
- 我有时间:
2017-05-11 21:00:00
- 其次,我想在这个时间上增加 24 小时:
2017-05-12 21:00:00
第三,我想从当前时间计算到2017-05-12 21:00:00的 - 剩余时间(例如当前时间为2017-05-11 22:10:00(:
22 hours and 50 minutes
那么我如何使用PHP来做到这一点呢?
使用 DateTime
<?php
$input = '2017-05-11 21:00:00';
$plus_24hrs = DateTime::createFromFormat('Y-m-d H:i:s', $input)->modify('+24 hour');
echo '+24hrs = ' . $plus_24hrs->format('Y-m-d H:i:s') . PHP_EOL;
$remaining = DateTime::createFromFormat('U', time());
$diff = $remaining->diff($plus_24hrs);
echo 'to go: ' . $diff->format('%hh %im %ss');
示例输出:
+24hrs = 2017-05-12 21:00:00
to go: 12h 24m 32s
演示:https://eval.in/792876
希望这有帮助。
我不会直接发布工作代码,因为看起来您需要了解有关 PHP 函数的更多信息。给你。这 3 个功能将完成这项工作。strtotime date-diff date_add
首先,您需要将字符串转换为时间戳以进行计算,然后可以计算所需的所有内容。苹果对苹果。永远不要忘记。
Using date_create & date_diff
// Create date & add 24 hours to it
$datetime1 = date_create('2017-05-11 22:35:45');
date_add($datetime1, date_interval_create_from_date_string('1 day'));
// Create the ref date
$datetime2 = date_create('2017-05-11 21:00:00');
// Calculate the difference, & print a formatted version of it
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%r %d days %h hours %i minutes');
<?php
$starttime = strtotime('2017-05-11 21:00:00');
$starttimeformat = date('Y-m-d H:i:s', $starttime);
echo "Current Time:";
echo $starttimeformat;
echo '<br/>';
echo '<br/>';
$onedayadedtime_format = date('Y-m-d H:i:s', strtotime('+24 hours', $starttime));
echo "End Time after adding 24 hours:";
echo $onedayadedtime_format;
echo '<br/>';
echo '<br/>';
$currenttime = time();
$currenttimeformat = date('Y-m-d h:i:s', $currenttime);
echo "Current Time:";
echo $currenttimeformat;
echo '<br/>';
echo '<br/>';
$onedayadedtime_formatobject = date_create($onedayadedtime_format);
$currenttimeformatobject = date_create($currenttimeformat);
$datedifference = date_diff($onedayadedtime_formatobject , $currenttimeformatobject);
echo "Time difference between dates ";
echo $onedayadedtime_format.' and '.$currenttimeformat;
echo '<br/>';
echo '<br/>';
echo "Hours: ";
echo $datedifference->h;
echo '<br/>';
echo "Minutes: ";
echo $datedifference->i;
echo '<br/>';
echo "Seconds: ";
echo $datedifference->s;
echo '<br/>';
echo "Year: ";
echo $datedifference->y;
echo '<br/>';
echo "Month: ";
echo $datedifference->m;
echo '<br/>';
echo "Days: ";
echo $datedifference->d;
echo '<br/>';
?>