1

My date and time is separated so I combine them like this

$mergeDateTime = new DateTime($date.' '.$time);
$currentDateTime = $mergeDateTime->format('d-m-Y H:i A);

I'm trying to subtract 5 hours to it for example the date today is 08-02-2018 04:00 AM when subtracted it should be 07-02-2018 11:00 PM

What I tried is this $newDate = date('d-m-Y H:i A', strtotime($currentDateTime)- (5 * 3600));

But it returns a different result than what I'm expecting. Thank you in advance for the help!


UPDATE

I thought it was already okay

I tried this code date('d-m-Y H:i A', strtotime($mergeDateTime->format('d-m-Y H:i A')) - 60 * 60 * 5); But upon testing it to for example 11-02-2018 10:30 PM it should be 05:30 PM with the same date but I'm receiving 31-12-1969 20:00 PM

It looks like if the result is in same date it returns like that.

1

3 Answers 3

0

You can check out the DateTime::sub() method, but also be sure you're setting the correct Time Zone.

To be clear, you're going to want to do something like this:

$tz = new DateTimeZone('America/Los_Angeles'); // See: http://php.net/manual/en/timezones.php
$dt = new DateTime('now', $tz);
$di = new DateInterval('P5H');  // See DateInterval documentation for interval_spec given here
$currentDateTime = $dt->format('d-m-Y H:i A');
$dt->sub($di); // You can't use the return value here, since this modified the $dt object and returns it for chaining
$previousDateTime = $dt->format('d-m-Y H:i A');  // This now contains the new time
0

I found a solution from this link

I tried like this

date('d-m-Y H:i A', strtotime($mergeDateTime->format('d-m-Y H:i A')) - 60 * 60 * 5);

** Update

Regarding my issue that if they have the same date, is that my merge date and time is always have 12 hours format and not 24 hours so I chnage H to h and now its working fine

0

There are many approaches to it, some of the answers may end up with same result.... heres my 1 cent..
$currentDateTime = $mergeDateTime->format('d-m-Y H:i:s); $currentDate = date('d-m-Y', strtotime($currentDateTime)); $currentTime = date('H:i:s', strtotime($currentDateTime)); $hour_5 = '05:00:00';

$a = new DateTime($currentTime);
$b = new DateTime($hour_5);
$diff = $a->diff($b);
$updated_date = $diff->format("%H:%i:%s");
$new_date_time = $currentDate.' '.$updated_date;

I have not yet tested it but should give you an idea...hope this works

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.