简体   繁体   中英

Quicker way to convert UTC to EST and add 3 days to it

I have the following code, it works but is there a "cleaner" way, maybe less code?

$today = new DateTime();
$utc_today = date('Y-m-d', $today->format('U'));
$new_date = new DateTime($utc_today, new DateTimeZone('America/New_York'));
$new_date->add(new DateInterval('P3D'));
echo $new_date->format('m-d-Y');

If you just need to expresses the time right now, plus 3 days, in EST, then you're doing way too much work. All you need is a single statement:

$date = new DateTime("3 days", new DateTimeZone('America/New_York'));
echo $date->format("Y-m-d H:i:s\n");

If you are starting with an arbitrary UTC timestamp, then you need about 3 lines of code instead of just one:

// let us assume $inputTimestamp is the UTC time you want to play with
$date = new DateTime(null, new DateTimeZone('America/New_York'));
$date->setTimestamp($inputTimestamp);
$date->modify("3 days");
echo $date->format("Y-m-d H:i:s\n");

Alternatively, you could add 3 days worth of seconds to your timestamp and save a little code, but it is less readable that way:

$date = new DateTime(null, new DateTimeZone('America/New_York'));
$date->setTimestamp($inputTimestamp + (3*24*60*60) );
echo $date->format("Y-m-d H:i:s\n");

For date/time manipulation, I have found the PHP Relative Formats documentation to be very useful. It is definitely worth reviewing.

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