PHP: add seconds to a date

2019-01-19 09:36发布

I have $adate; which contains:

Tue Jan 4 07:59:59 2011

I want to add to this date the following:

$duration=674165; // in seconds

Once the seconds are added I need the result back into date format.

I don't know what I'm doing, but I am getting odd results.

Note: both variables are dynamic. Now they are equal to the values given, but next query they will have different values.

9条回答
smile是对你的礼貌
2楼-- · 2019-01-19 10:05
// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));
查看更多
倾城 Initia
3楼-- · 2019-01-19 10:06
echo date("Y-m-d H:i:s",strtotime('+1 Second'));
查看更多
男人必须洒脱
4楼-- · 2019-01-19 10:10
$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);
查看更多
甜甜的少女心
5楼-- · 2019-01-19 10:16

Do this:

$seconds = 1;
$date_now = "2016-06-02 00:00:00";

echo date("Y-m-d H:i:s", (strtotime(date($date_now)) + $seconds));
查看更多
可以哭但决不认输i
6楼-- · 2019-01-19 10:17

I have trouble with strtotime() to resolve my problem of add dynamic data/time value in the current time

This was my solution:

$expires = 3600; //my dynamic time variable (static representation here)
$date = date_create(date('Y-m-d H:i:s')); //create a date/time variable (with the specified format - create your format, see (1))
echo date_format($date, 'Y-m-d H:i:s')."<br/>"; //shows the date/time variable without add seconds/time
date_add($date, date_interval_create_from_date_string($expires.' seconds')); //add dynamic quantity of seconds to data/time variable
echo date_format($date, 'Y-m-d H:i:s'); //shows the new data/time value

font: https://secure.php.net/manual/en/datetime.add.php (consult Object Oriented style too, the Elzo Valugi solution)

(1) https://secure.php.net/manual/en/function.date.php

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-19 10:18

I made this example for a timezone, but if you change some parts it may help you out:

$seconds_to_add = 30;
$time = new DateTime();
$time->setTimezone(new DateTimeZone('Europe/London'));
$time2 = $time->format("Y/m/d G:i:s");
$time->add(new DateInterval('PT' . $seconds_to_add . 'S'));
$timestamp = $time->format("Y/m/d G:i:s");
echo $timestamp;
echo '========';
echo $time2;

Result:

2018/06/17 3:16:23========2018/06/17 3:15:53
查看更多
登录 后发表回答