PHP subtract unknown time from datetime - php

So, I'm creating a booking system. When I retrieve this booking from the database, I need to check if the current date and time is closer to the actual booked date and time.
On the admin dashboard, the admins specify how much time earlier the client can make a checkin, let's say for example, 30minutes. But this time can be different. Can be 1hour, 2hours, 10minutes.
When I get the result from the database I get them like this:
$date_schedule = '2021-03-25 15:40:00'; // Can be any date in the future as well;
$time_to_check = '00:30:00'; // Can be '01:05:00', whatever the admins set as time_to_check;
// Expected result
'2021-03-25 15:10:00';
I tried subtracting this but I didn't made it work.. This is what I did.
$current_date = date("Y-m-d H:i:s");
$booking_date = '2021-03-25 15:00:00'; // From database
$time_to_check = '00:30:00'; // From database
$hours = explode(':', $time_to_check);
$data_check = date($booking_date, strtotime('-' . $hours[0] . ' hour -' . $hours[1] . ' minutes'));
But with this, $data_check returns the same value as $booking_date, it's not subtracting the time.

Convert your date to DateTime to make some operations on it :
function changeDate($date, $interval) {
$datetime = new DateTime($date);
$values = explode(':', $interval);
$datetime->modify("-$values[0] hours -$values[1] minutes -$values[2] seconds");
return $datetime->format('Y-m-d H:i:s');
}
$date = changeDate('2021-03-25 15:00:00', '00:30:00');
echo $date; // 2021-03-25 14:30:00
$date = changeDate('2021-03-25 15:00:00', '01:30:00');
echo $date; // 2021-03-25 13:30:00
$date = changeDate('2021-03-25 15:00:00', '02:30:15');
echo $date; // 2021-03-25 12:29:45
You can find documentation here https://www.php.net/manual/en/book.datetime.php

Just convert the timestamp to Unix time, and then subtract 30 minutes in seconds (30 * 60) from the Unix time.
Like this:
$date = '2021-03-25 15:10:00';
$timestamp = strtotime($date);
$timestamp = ($timestamp - (30 * 60));
echo gmdate("Y-m-d H:i:s", $timestamp);
EDIT: If you are in an odd timezone, like me (GMT+0100) add or subtract difference;
$timestamp = (($timestamp - (30 * 60)) + (1 * 60 * 60))

Related

How to sum hours with existing datetime in PHP?

I have two fields which store data like 2018-03-26 11:20:35 and 02:25:10(2 hours 25 minutes and 10 seconds) first data is date and time. second one is only time. I want to sum it and finally my result should 2018-03-26 13:45:45
How to do that in php code?
I have tried this way:
<?php
$date = '2018-03-26 11:20:35';
//echo $date;
//echo "<br>";
$hours = '02:25:10'; /* this data dynamic */
$sumTime = strtotime($date) + strtotime($hours);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Output:
Warning: date() expects parameter 2 to be integer, float given in C:\my-project-path\test.php on line 7
Here's a simple solution, some checks are skipped:
// convert your date to DateTime object
$date = '2018-03-26 11:20:35';
$dt = new DateTime($date);
// convert your period to DateInterval
$hours = '02:25:10'; /* this data dynamic */
$parts = explode(':', $hours);
$interval = new DateInterval('PT' . (int)$parts[0] . 'H' . $parts[1] . 'M' . $parts[2] . 'S');
// Add interval to date
$dt->add($interval);
// Format date as you need
echo $dt->format('Y-m-d H:i:s');
You could create a duration in seconds by comparing today at "00:00:00" and today at $hours. Actually, strtotime($hours) returns the timestamp of today at $hours, so, the addition of the two timestamp don't give the expected result.
If $hours is lesser than 24 hours, you could use:
$date = '2018-03-26 11:20:35';
$hours = '02:25:10';
$d0 = strtotime(date('Y-m-d 00:00:00'));
$d1 = strtotime(date('Y-m-d ').$hours);
$sumTime = strtotime($date) + ($d1 - $d0);
$new_time = date("Y-m-d H:i:s", $sumTime);
echo $new_time;
Outputs:
2018-03-26 13:45:45
You should check DateTime::add:
http://php.net/manual/en/datetime.add.php
http://php.net/manual/en/datetime.examples-arithmetic.php
Example:
<?php
// Convert h:m:s format to PThHmMsS format
sscanf('02:25:10', '%d:%d:%d', $hour, $minute, $second);
$intervalSpec = sprintf('PT%dH%dM%dS', $hour, $minute, $second);
$datetime = new DateTimeImmutable('2018-03-26 11:20:35');
$newDatetime = $datetime->add (new DateInterval($intervalSpec));
echo $newDatetime->format(DateTime::W3C);
It could be done with some simple string manipulation:
$dt = new DateTime("$date UTC");
$modify = preg_replace('/:/', ' hours ', $hours, 1);
$modify = preg_replace('/:/', ' minutes ', $modify, 1);
$modify .= ' seconds';
$dt->modify($modify);
demo
If you have MySQL as your data storage, you could do:
DATE_ADD(field1, INTERVAL field2 HOUR_SECOND)
demo
you can do something like:
$hour = $hours->format('H'); //This way you get a string which contains the hours
$date->modify('+'.$hour.' hour'); //you modify your date adding the hours
I'm assuming you only need the hours, and not minutes and seconds
EDIT:
you can do like that using regexp
$date = new \DateTime('2018-03-26 11:20:35');
$hours ='02:25:10';
preg_match("/^([0-9].*):([0-9].*):([0-9].*)/",$hours,$matches);
$date->modify('+'.$matches[1].' hour');
$date->modify('+'.$matches[2].' minute');
echo $date->modify('+'.$matches[3].' second')->format('Y-m-d H:i:s');

Convert an Unix timestamp to good GMT date PHP

I want to get the FRENCH GMT DATE from an Unix timestamp.
In my database, i saved the date in GMT+0 then i get the timestamp of this date and want to display the date with the good GMT+2
My timestamp is :1461857633 from database and it's equal to : 29/04/2016 12:27:11
And now i want to display this date with local GMT.
So i did this :
$timestamp = 1461857633;
$format = 'd/m/Y H:i:s';
$res = date($format, $timestamp);
echo $res;
and i have the same date 29/04/2016 12:27:11 where as my timezone is well 'Europe/Paris'
Normaly i should to have this date : 29/04/2016 14:27:11
$timestamp = 1461857633;
$effectiveDate = strtotime("+120 minutes", $timestamp);
$format = 'd/m/Y H:i:s';
$res = date($format, $effectiveDate);
echo $res;
date_default_timezone_set("UTC");
$HUTC = date("h");
date_default_timezone_set("Europe/Paris");
$HParis = date("h");
$diff = $HParis - $HUTC;
$timestamp = 1461857633;
$timestamp = 1461857633 + $diff * 60 * 60;
$format = 'd/m/Y H:i:s';
$res = date($format,$timestamp);
echo $res;
This will work both summer and winter time
You can simply add 2 hours to the timestamp or you can create a DateTime object and modify it by adding 2 hours to it:
$timestamp = 1461857633 + 2 * 60 * 60;
or
$dateTime = new DateTime();
$dateTime->setTimestamp(1461857633)->modify('+2 hours');
echo $dateTime->format('d/m/Y H:i:s');
or, another solution would be to calculate the seconds between the timezone you want to convert to and the Greenwich time zone (which is GMT+0) like:
$greenwichTimeZone = new DateTimeZone('Greenwich Mean Time');
$parisTimeZone = new DateTimeZone('Europe/Paris');
$dateTimeGreenwich = new DateTime('now', $greenwichTimeZone);
$seconds = $parisTimeZone->getOffset($dateTimeGreenwich);
$dateTime = new DateTime();
$dateTime->setTimestamp(1461857633 + $seconds);
echo $dateTime->format('d/m/Y H:i:s');

Subtract minutes from date using strtotime

I have the current date format $date = 'yyyy-mm-dd hh:mm' and notice that $date is already set and not using the Date class. I understand I have to use strtotime which I have done to my $date $datestr = strtotime($date). I wish to subtract 5 minutes to the set time.
I've tried this simple thing $A = strtotime($date) - strtotime('-5 min'); But it does not aid me.
its simple to subtract the seconds of 5 minutes which is (5*60)=300 from your time
like this
$time = strtotime($date);
$time_new = $time-(5*60); // will time of the -5 min from the current $time
example
$date = date('d-M-Y g:i:s A'); // current date
echo $date."<br/>"; // output : 17-Feb-2014 8:35:58 AM
$time = strtotime($date); // convert current date to timestamp
$time_new = $time - (5*60); // subtract 5 minutes from current time.
$date_new = date('d-M-Y g:i:s A', $time_new); // convert time to the date again
echo $date_new; // output : 17-Feb-2014 8:30:58 AM

How to Subtract Minutes

I want to send a reminder email.I don't want to use cron on Linux/Unix/BSD box or Scheduled Tasks on Windows.
I'm trying to subtract 15 minutes from the current time.
here is my code so far (doesn't work):
$days = date("j",time());
$months = date("n",time());
$years = date("Y",time());
$hours = date("G",time());
$mins = (date("i",time()));
$secs = date("s",time());
$mins = $mins-15;
To subtract 15 minutes from the current time, you can use strtotime():
$newTime = strtotime('-15 minutes');
echo date('Y-m-d H:i:s', $newTime);
Change the date into a timestamp (in seconds) then minus 15 minutes (in seconds) and then convert back to a date:
$date = date("Y-m-d H:i:s");
$time = strtotime($date);
$time = $time - (15 * 60);
$date = date("Y-m-d H:i:s", $time);
You can use DateInterval
$date = new DateTime();
$interval = new DateInterval("PT15M");
$interval->invert = 1;
$date->add($interval);
echo $date->format("c") . "\n";
you can try this as well,
$dateTimeMinutesAgo = new DateTime("15 minutes ago");
$dateTimeMinutesAgo = $dateTimeMinutesAgo->format("Y-m-d H:i:s");
How about substracting the 15 minutes from time() before converting it?
$time = time() - (15 * 60);
And then use $time instead of time() in your code.
$currentTime = date('Y-m-d H:i:s');
$before15mins = strtotime('-15 minutes');
echo date('Y-m-d H:i:s', $before15mins);
You can also use strtotime function to subtract days, hours and/or seconds from current time.
echo date('Y-m-d H:i:s', strtotime('-15 minutes'));
Following is the way you can add days / hours / minutes / sec to current time
$addInterval = date('Y-m-d H:i:s', strtotime("+$days days $hours hours $minute minute $sec second", strtotime(currentTime)));
You can also use DateInterval object
<?php
$date = new DateTime('Y-m-d H:i:s');
$date->sub(new DateInterval('PT10H30S'));
echo $date->format('Y-m-d H:i:s');?>
Try using
$min = time() - 900; //900 seconds = 15 minutes
To subtract 15 minutes you can do:
date('Y-m-d H:i:s', (time() - 60 * 15));
You can replace 15 with the number of minutes you want.
In case you're looking to subtract seconds you can simply do:
date('Y-m-d H:i:s', (time() - 10));
In this way you'll subtract 10 seconds.
If you have only time value than below will be useful
// Your time
$time = '12:15:00';
// Returned value '12:00:00'
$newTime = date('H:i:s', strtotime($time) - (15*60));
I know this question is outdated but i just want to share how i did it in easy way
$current = new DateTime("10 minutes ago", new DateTimeZone('Asia/Manila') );
echo $current->format("Y-m-d H:i:s");
//To Get Current DateTime
$currentDate = date("Y-m-d H:i:s");
//To Get Current DateTime - 15Min
$oldDate = date("Y-m-d H:i:s", strtotime($currentDate) - (15 * 60));
echo $currentDate;
echo $oldDate;

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

Categories