Reputation: 5147
I am trying to deduct 5 hours and 30 mins from the selected datetime but it is not working
my php code
$ambulanceDate = date('Y-m-d H:i:s', ($_POST['ambuStartDate'] . " " . $_POST['ambuStartTime']));
$date1 = str_replace('-', '/', $ambulanceDate);
$ambulanceUpdatedDate = date('m-d-Y',strtotime($date1 . "-5 hours 30 minutes"));
$ambulanceUpdatedDate = new DateTime($ambulanceUpdatedDate);
Upvotes: 0
Views: 154
Reputation: 1453
Use modify
function with DateTime
reference:
<?php
$ambulanceDate = date('Y-m-d H:i:s', ($_POST['ambuStartDate'] . " " . $_POST['ambuStartTime']));
$date_time = new DateTime($ambulanceDate);
$date_time->modify('-5 hours');
$date_time->modify('-30 minutes');
$ambulanceUpdatedTime = $date_time->format('m-d-Y H:i:s');
echo $ambulanceDate . PHP_EOL;
echo '-5h 30mins:' . PHP_EOL;
echo $ambulanceUpdatedTime;
Output:
2017-04-11 05:22:07
-5h 30mins:
04-10-2017 23:52:07
Demo here: https://eval.in/772567
Refined since question really wants to convert a local time to UTC time:
<?php
date_default_timezone_set('Asia/Kolkata');
//$ambulanceDate = date('Y-m-d H:i:s', ($_POST['ambuStartDate'] . " " . $_POST['ambuStartTime']));
$ambulanceDate = date('Y-m-d H:i:s', time());
$indian_time = new DateTime($ambulanceDate);
$utc_time = new DateTime($ambulanceDate);
$ambulanceUpdateTime = $utc_time
->setTimezone(new DateTimeZone('UTC'))
->format('m-d-Y H:i:s');
echo 'Indian time: ' . $indian_time->format('m-d-Y H:i:s') . PHP_EOL;
echo 'UTC time: ' . $ambulanceUpdateTime;
Demo of this: https://eval.in/772648
Upvotes: 1
Reputation: 22911
Why would you even do $date1 = str_replace('-', '/', $ambulanceDate);
? Couldn't you just do date('Y/m/d H:i:s'
...
This should do it:
//Change 'Y-m-d H:i:s' with the format of your ambuStartDate, and ambuStartTime.
$ambulanceDate = DateTime::createFromFormat('Y-m-d H:i:s', ($_POST['ambuStartDate'] . " " . $_POST['ambuStartTime']));
$ambulanceUpdatedDate = $ambulanceDate->sub(new DateInterval('P5DT30M'));
//Format it how you like:
$formattedUpdatedDate = $ambulanceUpdatedDate->format('m-d-Y h:iA');
Upvotes: 1