PHP: add seconds to a date - php

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.

If you are using php 5.3+ you can use a new way to do it.
<?php
$date = new DateTime();
echo $date->getTimestamp(). "<br>";
$date->add(new DateInterval('PT674165S')); // adds 674165 secs
echo $date->getTimestamp();
?>

Just use some nice PHP date/time functions:
$adate="Tue Jan 4 07:59:59 2011";
$duration=674165;
$dateinsec=strtotime($adate);
$newdate=$dateinsec+$duration;
echo date('D M H:i:s Y',$newdate);

Given the fact that $adate is a timestamp (if that's the case), you could do something like this:
$duration = 674165;
$result_date = strtotime(sprintf('+%d seconds', $duration), $adate);
echo date('Y-m-d H:i:s', $result_date);

// add 20 sec to now
$duration = 20;
echo date("Y-m-d H:i:s", strtotime("+$duration sec"));

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));

$current_time_zone = 150;
date("Y-m-d H:i:s",strtotime(date("Y-m-d H:i:s"))+$current_time_zone);

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

It would be easier with DateTime::modify
(new DateTime($str))->modify("+$duration seconds"); //$str is the date in string

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

Related

PHP Minus time in Format

I want to keep the H:i:s format so 10:52:20 however when I try:
$timeleft = strtotime($time1)-strtotime($time2);
I get something like 4521
I would like the result to retain the format. Is there a way to do this?
Yeah, what you get is unix timestamp which is in seconds. You can use date function to get required format like this:
$timestr_formated = date("H:i:s", $timeleft);
print($timestr_formated);
You can use DateTime::diff.
$time1 = new DateTime('2017-05-01 12:00:00');
$time2 = new DateTime('2017-05-01 11:25:30');
$timeleft = $time1->diff($time2);
echo $timeleft->format('%H:%i:%s'); // output: 00:34:30
In case you want to allow more than 24 hours.
$time1 = new DateTime('2017-05-02 12:00:00');
$time2 = new DateTime('2017-04-02 11:25:30');
$timeleft = $time1->diff($time2);
echo str_pad($timeleft->format('%a') * 24 + $timeleft->format('%h'), 2, "0") .
$timeleft->format(':%i:%s'); // output: 720:34:30
You can use date function by below format:
$timeleft = date('H:i:s', strtotime($time1)-strtotime($time2));

Get 30 days back date along with time

I want to calculate EXACT past 30 days time period in php from now (for example 30 aug 14 23:06) to 30 days back (for example 1 aug 14 23:06). I wrote this where current datetime goes in $d1 and past 30 days datetime goes in $d2 but somehow i am not getting correct results. Any idea?
$url=$row["url"];
$pageid=getPageID($url);
$date=date('y-m-d g:i');
$d1=strtotime($date);
$d2=date(strtotime('today - 30 days'));
Thanks
The problem is likely caused by the malformed date() call. The first argument passed to date() should be the format (as shown in the Docs) and the second should be an optional timestamp.
Try this:
$d2 = date('c', strtotime('-30 days'));
PHPFiddle
As a short aside, the whole snippet can be simplified as follows:
$url = $row["url"];
$pageid = getPageID($url);
$date = date('y-m-d g:i');
$d1 = time();
$d2 = date('y-m-d g:i', strtotime('-30 days'));
You can also use the DateTime class's sub() method together with an DateInterval:
$now = new DateTime();
$back = $now->sub(DateInterval::createFromDateString('30 days'));
echo $back->format('y-m-d g:i');
if you would like to get out put as 2014-08-01 then try the below code. thanks
$date = '2014-08-30 23:06';
$new_date = date('Y-m-d G:i', strtotime($date.' - 29 days'));
echo "30 days back is " . $new_date;
From your brief description and example given, I believe that you want the date to be 30 days back and time to be the same as of now. The below code will serve this purpose. Thanks.
<?php
$date=date('y-m-d g:i');
$time=date('g:i');
echo "Todays date:" . $date. "<br>";
$d2 = date('y-m-d', strtotime('-30 days'));
echo "30 days back:" . $d2 . ' ' .$time;
?>
Try:
echo date("Y-m-d h:i:s",strtotime('-30 days'));
For more detail click here
Very simple two lines of code
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
I know you said with PHP, however, I can't imagine not getting the records from a DB. If you want to do so from the DB,use:
$sql='SELECT * FROM myTable WHERE date > CURRENT_DATE - INTERVAL 30 DAY';
$pdo->query($sql);
Very simple one lines of code:
echo (new DateTime())->modify('-30 day')->format('y-m-d g:i');
In the example below, it makes no sense if the variable $date is not
used anywhere else!
$date = new DateTime();
echo $date->modify('-30 day')->format('y-m-d g:i');
Sample answer is
$dateBack30Days=date('Y-m-d g:i', strtotime('-30 days'));

How to create human readable time stamp?

In my PHP program, I'm using $_SERVER to log the page's date visited:
$dateStamp = $_SERVER['REQUEST_TIME'];
The result is that the $dateStamp variable contains a Unix timestamp like:
1385615749
What's the simplest way to convert it into a human-readable date/time (with year, month, day, hour, minutes, seconds)?
This number is called Unix time. Functions like date() can accept it as the optional second parameter to format it in readable time.
Example:
echo date('Y-m-d H:i:s', $_SERVER['REQUEST_TIME']);
If you omit the second parameter the current value of time() will be used.
echo date('Y-m-d H:i:s');
Your functional approch to convert timestamp into Human Readable format are as following
function convertDateTime($unixTime) {
$dt = new DateTime("#$unixTime");
return $dt->format('Y-m-d H:i:s');
}
$dateVarName = convertDateTime(1385615749);
echo $dateVarName;
Output :-
2013-11-28 05:15:49
Working Demo
<?php
$date = new DateTime();
$dateStamp = $_SERVER['REQUEST_TIME'];
$date->setTimestamp($dateStamp);
echo $date->format('U = Y-m-d H:i:s') . "\n";
?>
you can try this
<?php
$date = date_create();
$dateStamp = $_SERVER['REQUEST_TIME'];
date_timestamp_set($date, $dateStamp);
echo date_format($date, 'U = D-M-Y H:i:s') . "\n";
?>
this code will work for you
$dateStamp = $_SERVER['REQUEST_TIME'];
echo date('d-M-Y H:i:s',strtotime($dateStamp));
REQUEST_TIME - It is unix timestamp - The timestamp of the start of the request.
$dateStamp = $_SERVER['REQUEST_TIME'];
echo date('d m Y', $dateStamp);
OR
$date = new DateTime($dateStamp);
echo $date->format('Y-m-d');

Adding minutes to date time in PHP

I'm really stuck with adding X minutes to a datetime, after doing lots of google'ing and PHP manual reading, I don't seem to be getting anywhere.
The date time format I have is:
2011-11-17 05:05: year-month-day hour:minute
Minutes to add will just be a number between 0 and 59
I would like the output to be the same as the input format with the minutes added.
Could someone give me a working code example, as my attempts don't seem to be getting me anywhere?
$minutes_to_add = 5;
$time = new DateTime('2011-11-17 05:05');
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$stamp = $time->format('Y-m-d H:i');
The ISO 8601 standard for duration is a string in the form of P{y}Y{m1}M{d}DT{h}H{m2}M{s}S where the {*} parts are replaced by a number value indicating how long the duration is.
For example, P1Y2DT5S means 1 year, 2 days, and 5 seconds.
In the example above, we are providing PT5M (or 5 minutes) to the DateInterval constructor.
PHP's DateTime class has a useful modify method which takes in easy-to-understand text.
$dateTime = new DateTime('2011-11-17 05:05');
$dateTime->modify('+5 minutes');
You could also use string interpolation or concatenation to parameterize it:
$dateTime = new DateTime('2011-11-17 05:05');
$minutesToAdd = 5;
$dateTime->modify("+{$minutesToAdd} minutes");
$newtimestamp = strtotime('2011-11-17 05:05 + 16 minute');
echo date('Y-m-d H:i:s', $newtimestamp);
result is
2011-11-17 05:21:00
Live demo is here
If you are no familiar with strtotime yet, you better head to php.net to discover it's great power :-)
You can do this with native functions easily:
strtotime('+59 minutes', strtotime('2011-11-17 05:05'));
I'd recommend the DateTime class method though, just posted by Tim.
I don't know why the approach set as solution didn't work for me.
So I'm posting here what worked for me in hope it can help anybody:
$startTime = date("Y-m-d H:i:s");
//display the starting time
echo '> '.$startTime . "<br>";
//adding 2 minutes
$convertedTime = date('Y-m-d H:i:s', strtotime('+2 minutes', strtotime($startTime)));
//display the converted time
echo '> '.$convertedTime;
I thought this would help some when dealing with time zones too. My modified solution is based off of #Tim Cooper's solution, the correct answer above.
$minutes_to_add = 10;
$time = new DateTime();
**$time->setTimezone(new DateTimeZone('America/Toronto'));**
$time->add(new DateInterval('PT' . $minutes_to_add . 'M'));
$timestamp = $time->format("Y/m/d G:i:s");
The bold line, line 3, is the addition. I hope this helps some folks as well.
A bit of a late answer, but the method I would use is:
// Create a new \DateTime instance
$date = DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00');
// Modify the date
$date->modify('+5 minutes');
// Output
echo $date->format('Y-m-d H:i:s');
Or in PHP >= 5.4
echo (DateTime::createFromFormat('Y-m-d H:i:s', '2015-10-26 10:00:00'))->modify('+5 minutes')->format('Y-m-d H:i:s')
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");
Use strtotime("+5 minute", $date);
Example:
$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);
As noted by Brad and Nemoden in their answers above, strtotime() is a great function. Personally, I found the standard DateTime Object to be overly complicated for many use cases. I just wanted to add 5 minutes to the current time, for example.
I wrote a function that returns a date as a string with some optional parameters:
1.) time:String | ex: "+5 minutes" (default = current time)
2.) format:String | ex: "Y-m-d H:i:s" (default = "Y-m-d H:i:s O")
Obviously, this is not a fully featured method. Just a quick and simple function for modifying/formatting the current date.
function get_date($time=null, $format='Y-m-d H:i:s O')
{
if(empty($time))return date($format);
return date($format, strtotime($time));
}
// Example #1: Return current date in default format
$date = get_date();
// Example #2: Add 5 minutes to the current date
$date = get_date("+5 minutes");
// Example #3: Subtract 30 days from the current date & format as 'Y-m-d H:i:s'
$date = get_date("-30 days", "Y-m-d H:i:s");
one line mysql datetime format
$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");
One more example of a function to do this: (changing the time and interval formats however you like them according to this for function.date, and this for DateInterval):
(I've also written an alternate form of the below function.)
// Return adjusted time.
function addMinutesToTime( $dateTime, $plusMinutes ) {
$dateTime = DateTime::createFromFormat( 'Y-m-d H:i', $dateTime );
$dateTime->add( new DateInterval( 'PT' . ( (integer) $plusMinutes ) . 'M' ) );
$newTime = $dateTime->format( 'Y-m-d H:i' );
return $newTime;
}
$adjustedTime = addMinutesToTime( '2011-11-17 05:05', 59 );
echo '<h1>Adjusted Time: ' . $adjustedTime . '</h1>' . PHP_EOL . PHP_EOL;
Without using a variable:
$yourDate->modify("15 minutes");
echo $yourDate->format( "Y-m-d H:i");
With using a variable:
$interval= 15;
$yourDate->modify("+{$interval } minutes");
echo $yourDate->format( "Y-m-d H:i");

Time calculation in php (add 10 hours)?

I get the time:
$today = time();
$date = date('h:i:s A', strtotime($today));
if the current time is "1:00:00 am", how do i add 10 more hours to become 11:00:00 am??
strtotime() gives you a number back that represents a time in seconds. To increment it, add the corresponding number of seconds you want to add. 10 hours = 60*60*10 = 36000, so...
$date = date('h:i:s A', strtotime($today)+36000); // $today is today date
Edit: I had assumed you had a string time in $today - if you're just using the current time, even simpler:
$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already
$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.
see DateTime Class
(PHP 5 >= 5.2.0)
You can simply make use of the DateTime class , OOP Style.
<?php
$date = new DateTime('1:00:00');
$date->add(new DateInterval('PT10H'));
echo $date->format('H:i:s a'); //"prints" 11:00:00 a.m
$date = date('h:i:s A', strtotime($today . ' + 10 hours'));
(untested)
$date = date('h:i:s A', strtotime($today . " +10 hours"));
Full code that shows now and 10 minutes added.....
$nowtime = date("Y-m-d H:i:s");
echo $nowtime;
$date = date('Y-m-d H:i:s', strtotime($nowtime . ' + 10 minute'));
echo "<br>".$date;
In order to increase or decrease time using strtotime you could use a Relative format in the first argument.
In your case to increase the current time by 10 hours:
$date = date('h:i:s A', strtotime('+10 hours'));
In case you need to apply the change to another timestamp, the second argument can be specified.
Note:
Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.
So, the recommended way since PHP 5.3:
$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');
or using aliases:
$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours'));
$date = date_format($dt, 'h:i:s A');
In all cases the default time zone will be used unless a time zone is specified.

Categories