简体   繁体   中英

How to Substract time from datetime

I am using a timezone based script where there is deadline based on timezones. Say for example a deadline is on 7th July at 6PM for a person in IST timezone. The deadline should be 1:30 less than 6pm in Dubai as per their timezone.

I have already calculated the difference between the two timezone difference. I am stuck at deducting that calculated time from the deadline time.

I have saved the timezones in +5:40 +4:00 -4:00 this format instead of using php default ones.

Here's what I use to add and subtract time from a date. First of all, I get the date from the database and then convert it to a DateTime object.

$date = new DateTime($date);

I use add and a DateInterval to add time. Here's an example to add hours.

$date->add(new DateInterval("PT{$hoursToAdd}H"));

And here's and example to subtract hours intead:

$date->sub(new DateInterval("PT{$hoursToSubstract}H"));

Check this out to know how to work with DateInterval and add/subtract different times: http://php.net/manual/en/class.dateinterval.php

Can you explain a little more specifically what you want to do?

You want to subtract when data already on some var inside your script or you want the SQL query needed ?

If so maybe you can use this answer ---> How to subtract 3 hours from a datetime in MySQL?

The last answer of this post maybe is the one that fit the most what you need :

Assuming you have some timezone issue and know source and destination timezone, you could convert it like so

 SELECT DATE_FORMAT(CONVERT_TZ(x.date_entered, 'UTC', 'Europe/Berlin'), '%Y-%m-%d') AS date FROM x ORDER BY date ASC; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM