Reputation: 1591
Even though i'm working with php from a long time now this issue is making me really confused. Let me explain whats going on, Suppose i'm booking an appointment for a Client at: 2019-03-31 10:00:00
and the appointment is going to be of 15 minutes so what i do is i do add these 15 minutes to the starting time of appointment which is 10:00:00
, so that will turn up to be: 10:15:00
ending time of appointment, now what is happening is "ONLY" with date: 2019-03-31
(31st only)
the date functionality is adding an additional hour to the time it supposed to be so instead of: 10:15:00
it changes to: 11:15:00
, i did check everywhere there is no additional code above this code to change the hour i did add the below exact script main file is using in another file on same server and that just works fine with same date and same timing:
$txtstart_date = '2019-03-31';
$day_time = '10:00';
$hrmin = explode(":",$day_time);
$hours = '0';
$minut = '15';
$selected_date_time = new DateTime($txtstart_date.' '.$day_time.':00');
$selected_date_time = $selected_date_time->format('Y-m-d H:i:s');
$selected_hours = new DateTime($selected_date_time);
if($hours){
$selected_hours = $selected_hours->modify('+'.$hours.' hours');
}
if($minut){
$selected_hours = $selected_hours->modify('+'.$minut.' minutes');
}
$selected_hours = $selected_hours->format('Y-m-d H:i:s');
echo date('Y-m-d H:i:s',strtotime($selected_hours));
it would be really great if anyone could clear the doubt here.
Upvotes: 0
Views: 49
Reputation: 1473
As mentioned by RiggsFolly, the problem might be the summer time. To prevent PHP to do weird stuff, do all the modification in one step. So you skip the part of parsing a string to a date, format it back to a string and parse it again as date:
$txtstart_date = '2019-03-31';
$day_time = '10:00';
$hours = '0';
$minutes = '15';
$datetime = $txtstart_date . ' ' . $day_time;
echo DateTime::createFromFormat('Y-m-d H:i', $datetime)
->modify('+' . $hours . ' hour')
->modify('+' . $minutes . ' minute')
->format('Y-m-d H:i:s');
If you need the same date twice so you can modify one, just clone it:
$baseTime = DateTime::createFromFormat('Y-m-d H:i', $datetime);
$toBeModified = clone $baseTime;
echo $baseTime->format('Y-m-d H:i:s') . PHP_EOL;
echo $toBeModified
->modify('+' . $hours . ' hour')
->modify('+' . $minutes . ' minute')
->format('Y-m-d H:i:s') . PHP_EOL;
It's also possible to change the used timezone of a DateTime object (which can be pretty useful in a database context when the dates stored in the database are utc):
echo DateTime::createFromFormat('Y-m-d H:i', $datetime, new DateTimeZone('Europe/London'))
->setTimezone(new DateTimeZone('UTC'))
->format('Y-m-d H:i:s');
Upvotes: 2
Reputation: 1702
I'm guessing it has something to do with this line right here:
if($hours){
$selected_hours = $selected_hours->modify('+'.$hours.' hours');
}
I would var_dump hours and see if it's set then trace it back to where its set.
Upvotes: -1