Add minutes to current time - php

I am trying to add minutes to current date but it returns strange results
date_default_timezone_set('Asia/Karachi');
$currentDate = date("m-d-Y H:i:s");
$currentDate_timestamp = strtotime($currentDate);
$endDate_months = strtotime("+10 minutes", $currentDate_timestamp);
$packageEndDate = date("m-d-Y H:i:s", $endDate_months);
echo " <br> " . $packageEndDate . " <br> ";
echo $currentDate;
I am getting Output
01-01-1970 05:50:00
07-19-2013 20:25:23
It should return
07-19-2013 20:35:23
07-19-2013 20:25:23
After this I need to query to database so date format should be same. Database column is of string type.

Your code is redundant. Why format a timestamp as a string, then convert that string back to a timestamp?
Try
$now = time();
$ten_minutes = $now + (10 * 60);
$startDate = date('m-d-Y H:i:s', $now);
$endDate = date('m-d-Y H:i:s', $ten_minutes);
instead.

Probably the minimalist way would be:
date_default_timezone_set('Asia/Baku');
$packageEndDate = date('Y-m-d H:i:s', strtotime('+10 minute'));
echo $packageEndDate;
Output (Current time in my city at the time of writing):
2017-07-20 12:45:17

Try this:
$now = time();
$tenMinFromNow = date("m-d-Y H:i:s", strtotime('+10 minutes', $time));

$tenMinsFromNow = (new \DateTime())->add(new \DateInterval('PT10M'));
Will leave you with a DateTime object representing a time 10 minutes in the future. Which will allow you to do something like:-
echo $tenMinsFromNow->format('d/m/Y H:i:s');
See it working
PHP version >= 5.4 I'm afraid, but you should be using at least that version by now anyway.

Pakistan, which is the localisation explicitly set, uses "DD-MM-YYYY" format dates so the problem occurs when you cast the date into a string of "MM-DD-YYYY". This American format of date is not parseable by the Pakistan localisation.
If you still want to keep the round-trip to a string and back, use DD-MM-YYYY or the ISO datetime format.
While this is the only (current) answer which actually explains your original issue, I recommend the code be refactored as others have demonstrated.

Related

How to get next time occurrence from now, submitted in php?

I have an input file with type time. what I want to do is to get time from the moment now that is if time right now is 2019-11-26 23:50:00 and the value of input field if 22:30:00, I should get a date 2019-11-27 22:30:00.
How can achieve this in PHP? in short, get the datetime stamp for the next occurrence of 22:30:00 which is 2019-11-27 22:30:00 as per the given example.
answer found but can we optimize the code more ?
$a = explode(':', date('H:i:s', strtotime($validateData['time'])));
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds';
$trigger_at = date(date('Y-m-d H:i:s', strtotime( $str, strtotime($validateData['date']))));
return $trigger_at;
This is simpler and a lot more readable
$time = "21:30:00"; // Time from input
$today = date("Y-m-d $time");
$tomorrow = date("Y-m-d H:i:s", strtotime($today)+86400);
$date = strtotime($today) < strtotime("now") ? $tomorrow : $today;
Explanation: We take timestamp at specified hour for today and tomorrow, if today timestamp has been passed, we use tomorrow timestamp. Simple. :)
All you are doing is appending (concatenating) a string onto another string.
$time = "22:30:00"; // This is the time you have
$date = date("Y-m-d"); // Right now in yyyy-mm-dd format.
$newdatetime = $date.' '.$time;
That will give you the current date with the supplied time appended to it. You can convert that back into a timestamp using:
$timestamp = strtotime($newdatetime);
The answer below is based on the original question in which the time was assumed to be an offset from now. It is left here simply to avoid deleting a lot of code.
The function strtotime is easy to use for that. However, it doesn't accept HH:MM:SS format. So, you have to alter the string. I would do it like:
$time = "22:30:00"; // This is the time you have
$a = explode(':', $time);
$str = '+'.$a[0].' hours '.$a[1].' minutes '.$a[2].' seconds'; // This breaks it into separate numbers with labels.
$date = date("Y-m-d h:i:s", strtotime($str)); // The adjusted date
You can change the format of the output as you like by changing the first string used in the date function.

Convert Now and Ten Minutes Ago to Different Timezone

I would like to convert the timestamps from ten minutes ago and now to match the following format:
2018-09-23T04:47:07.237
Here are the timestamps I'd like to convert to match the above format:
$now = date('m/d/y g:i a');
$now = strtotime($now);
$ten_minutes_ago = strtotime('-10 minutes');
How can I do this? Thanks!
Use date_format function instead. You don't need to convert to UNIX timestamp using strtotime function. Instead use DateTime library
Check the following (Rextester Demo):
$now = new DateTime(); // create a datetime object
$sub = new DateInterval("PT10M"); // Interval of 10 mins
$ten_minutes_ago = new DateTime();
$ten_minutes_ago->sub($sub); // subtract 10 minutes
// changed formats
$now_changed = date_format($now, DATE_ISO8601);
$ten_minutes_ago_changed = date_format($ten_minutes_ago, DATE_ISO8601);
// print output
echo $now_changed; //2018-09-23T02:58:25-0400
echo $ten_minutes_ago_changed; // 2018-09-23T02:48:25-0400
Details:
The date_format() function returns a date formatted according to the specified format.
DATE_ISO8601 - ISO-8601 (example: 2013-04-12T15:52:01+0000)
You can check for more formatting options here.
Here is how I would do what you are asking for.
If your data is in a string. Here is the only line of code you need:
$date = date('m/d/y g:i a'); //Gets a date string.
echo substr(date('Y-m-d\TH:i:s.u', strtotime($date . ' -10 minutes')), 0, -3); // PHP < 7.0.0
//echo date('Y-m-d\TH:i:s.v', strtotime($date . ' -10 minutes')); //PHP > 7.0.0
This will produce:
Ex.
09/23/18 12:13 am
To
2018-09-23T00:03:00.000
One thing to note here. The microseconds will always be zeros if your original input date is a string and in the format m/d/y g:i a that you have specified. The reason being is that there is no millisecond information to be had from the date string.
If you create you input date as a dateTime object, the object will be able to keep track of the microseconds for you.

Difference between timestamps in minutes in PHP

I want to get difference between 2 timestamps of format Y-m-d H:i:s in minutes in PHP.
The code used is,
$currentDate = date('Y-m-d H:i:s');
$userLastActivity = date($date);
$timeLapse = (($currentDate - $userLastActivity)/60);
Here, $date is obtained from database.
The value of $timeLapse is 0 in output. Please help.
Try using unix timestamp. Practically it measures the time in seconds from 1/1/1970 and it's a lot easier to use and understand than a php object.
$currentTimestamp = new DateTime()->getTimestamp();
$userLastActivity = date($date)->getTimestamp();
$timeLapse = (($currentDate - $userLastActivity)/60);
You should have the time saved as timestamp on the server too, in that case you could use the $date directly as a number, with no need for a conversion. And also, because it's universal, you can pass it around to javascript or any other language without any worries for conversion
Use strtotime to parse textual datetime into a Unix timestamp and substract $userLastActivity from $currentDate and divide by 60.
See if this helps -
<?php
$currentDate = strtotime(date('Y-m-d H:i:s'));
$date = "2016-10-11 02:40:50";
$userLastActivity = strtotime($date);
echo round(abs($currentDate - $userLastActivity) / 60). " minutes";
?>
For more details :strtotime
Change these 2 lines for a start, as I don't think dividing dates by 60 is gonna work to well.
$currentDate = time();
$userLastActivity = strtotime($date);
That way you have time stamps and not dates (string)

Add days to a timestamp

Im trying to add a certain amount of days to a timestmp using this in PHP:
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate);
$endDate2 = strtotime('+1 day',$endDate);
echo $endDate2;
but its displaying: 1216526400
any ideas?
Try:
echo date("Y-m-d H:i:s",$endDate2);
Or (for just the date):
echo date("Y-m-d",$endDate2);
You can find documentation about how to format your string here: http://php.net/manual/en/function.date.php
You should be using DateTime for working with dates. It's timezone friendly.
$datetime = new DateTime('2008-06-20');
$datetime->modify('+1 day');
echo $datetime->getTimestamp();
strtotime() converts the date into a unix timestamp which is the number of seconds since January 1st 1970. If you want a date output you have to run the finished timestamp through date() first.
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate.' +1 day');
echo date("Y-m-d", $endDate);
strtotime creates a Unix timestamp so if you want to be presented with a formatted date, you need to pass the timestamp as an argument to the date function as follows:
$capturedDate = '2008-06-20';
$endDate = strtotime($capturedDate);
$endDate2 = strtotime('+1 day',$endDate);
echo date('Y-m-d', $endDate2);
Additionally, there are a wide variety of parameters you can use in the date function if you want to display additional information.
e.g.: echo date('Y-m-d H:i:s', $endDate2); or echo date('Y-m-d h:i:s a', $endDate2);, etc.
Sooooo close, just take your timestamp and convert it back into date format using date("desired format",$endDate2);
DateTime is a very nice way to deal with dates. You can try like this:
$capturedDate = '2008-06-20';
$date = DateTime::createFromFormat('Y-m-d', $capturedDate)->modify('+1 day');
echo $date->getTimestamp();

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

Categories