Home > Mobile >  date_format() with timezone
date_format() with timezone

Time:08-24

I have in database timestamp but need to add 2 hours to the current timezone.

Here is my code

<?= date_format(date_create($new['date_created']), "d/m/Y H:I") ?>

and output 23/08/2022 09:31 need to be 23/08/2022 11:31

CodePudding user response:

date_create(), date_format(), and most [but not all] other date_*() functions are just the procedural interfaces for interacting with DateTime objects. However, there is a lot of DateTime functionality that is simply not exposed procedurally, eg: properly modifying the timezone on a DateTime object.

$input = '2022-08-23 13:35:00';

// infer the format. not great, works _most_ of the time, until it doesn't.
$dt = new DateTime($input);

// explicitly specify the format so that it _always_ works
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $input);

// wait, what's the timezone? the above leave it out and use the system default, but this is another thing you should specify
$system_tz = new DateTimezone('America/New_York');

// equivalent to the previous, but with timezones
$dt = new DateTime($input, $system_tz);
$dt = DateTime::createFromFormat('Y-m-d H:i:s', $input, $system_tz);

printf("System date: %s\n", $dt->format("d/m/Y H:i"));
printf("System date: %s\n", $dt->format("c"));

// now to modify it to somewhere else
$user_tz = new DateTimezone('America/Los_Angeles');
$dt->setTimezone($user_tz);

printf("\n");
printf("  User date: %s\n", $dt->format("d/m/Y H:i"));
printf("  User date: %s\n", $dt->format("c"));

Output:

System date: 23/08/2022 13:35
System date: 2022-08-23T13:35:00-04:00

  User date: 23/08/2022 10:35
  User date: 2022-08-23T10:35:00-07:00

Put succintly:

$input = '2022-08-23 13:35:00';
$system_tz = new DateTimezone('America/New_York');
$user_tz = new DateTimezone('America/Los_Angeles');
$date_str = DateTime::createFromFormat('Y-m-d H:i:s', $input, $system_tz)
    ->setTimezone($user_tz)
    ->format("d/m/Y H:i");

It is especially important that you do not treat timezone conversions as simply plus/minus a number of hours as the rules that govern timezones across various localities can be wildly granular and inconsistent. Always use available date library functions.

Ref:

CodePudding user response:

You can select your server's dateTimeZone and use DateInterval to add the amount of time you want.

example:

 $hoursDB = date_format(date_create($new['date_created']), "d/m/Y H:I");
 $now = new DateTime($hoursDB); 
 $now->add(new DateInterval('PT2H')); // add 2 hours
 $dateTimeNew = $now->format('Y-m-d H:i');

outPut 2022-08-24 04:32:45

Links: DateTime : https://www.php.net/manual/en/class.datetime DateInterval : https://www.php.net/manual/en/class.dateinterval.php

  • Related