Adding 1 hour to time variable

后端 未结 10 1208
南笙
南笙 2020-12-05 06:27

I have a time to which I want to add an hour:

$time = \'10:09\';

I\'ve tried:

$time = strtotime(\'+1 hour\');

strtotime(\'+1          


        
相关标签:
10条回答
  • 2020-12-05 06:48

    You can try this code:

    $time = '10:09';
    
    echo date( 'H:i', strtotime( '+1 hour' , strtotime($time) ) );
    
    0 讨论(0)
  • 2020-12-05 06:50

    for this problem please follow bellow code:

    $time= '10:09';
    $new_time=date('H:i',strtotime($time.'+ 1 hour'));
    echo $new_time;`
    // now output will be: 11:09
    
    0 讨论(0)
  • 2020-12-05 06:50

    You can use:

    $time = strtotime("10:09") + 3600;
    echo date('H:i', $time);
    

    Or date_add: http://www.php.net/manual/en/datetime.add.php

    0 讨论(0)
  • 2020-12-05 06:52
    $time = '10:09';
    $timestamp = strtotime($time);
    $timestamp_one_hour_later = $timestamp + 3600; // 3600 sec. = 1 hour
    
    // Formats the timestamp to HH:MM => outputs 11:09.
    echo strftime('%H:%M', $timestamp_one_hour_later);
    // As crolpa suggested, you can also do
    // echo date('H:i', $timestamp_one_hour_later);
    

    Check PHP manual for strtotime(), strftime() and date() for details.

    BTW, in your initial code, you need to add some quotes otherwise you will get PHP syntax errors:

    $time = 10:09; // wrong syntax
    $time = '10:09'; // syntax OK
    
    $time = date(H:i, strtotime('+1 hour')); // wrong syntax
    $time = date('H:i', strtotime('+1 hour')); // syntax OK
    
    0 讨论(0)
  • 2020-12-05 06:54

    You can do like this

        echo date('Y-m-d H:i:s', strtotime('4 minute'));
        echo date('Y-m-d H:i:s', strtotime('6 hour'));
        echo date('Y-m-d H:i:s', strtotime('2 day'));
    
    0 讨论(0)
  • 2020-12-05 06:54

    2020 Update

    It is weird that no one has suggested the OOP way:

    $date = new \DateTime(); //now
    $date->add(new \DateInterval('PT3600S'));//add 3600s / 1 hour
    

    OR

    $date = new \DateTime(); //now
    $date->add(new \DateInterval('PT60M'));//add 60 min / 1 hour
    

    OR

    $date = new \DateTime(); //now
    $date->add(new \DateInterval('PT1H'));//add 1 hour
    

    Extract it in string with format:

    var_dump($date->format('Y-m-d H:i:s'));
    

    I hope it helps

    0 讨论(0)
提交回复
热议问题