添加24小时到文本时间并使用PHP计算剩余时间

时间:2017-05-12 08:20:50

标签: php

美好时光
我有一个像2017-05-11 22:35:45的文字时间,我想在这个时间增加24小时并计算剩余时间 E.x:

  1. 我有时间:2017-05-11 21:00:00
  2. 其次我希望在此时间内添加24小时:2017-05-12 21:00:00
  3. 第三我想计算从当前时间到21:00:00的剩余时间(例如当前时间是2017-05-11 22:10:00):22 hours and 50 minutes
  4. 那我怎么能用PHP做呢?

4 个答案:

答案 0 :(得分:1)

使用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

希望这有帮助。

答案 1 :(得分:0)

我不会直接发布工作代码,因为您需要了解有关PHP函数的更多信息。干得好。这3个功能将完成这项工作。 strtotime date-diff date_add

首先,您需要将字符串转换为时间戳以进行计算,然后您可以计算所需的所有内容。苹果到苹果。永远不要忘记。

答案 2 :(得分:0)

使用date_create&amp; 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');

答案 3 :(得分:0)

 <?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/>';

    ?>