0

I have a situation where I need to conditionally correct the default timezone defined in a drupalDatetime object. But I'm clearly not understanding how to do it properly. Example:

use Drupal\Core\Datetime\DrupalDateTime;

// Sample DateTime Object
$test_date = new DrupalDateTime('2022-09-27T13:30');
// Output 2022-09-27 13:30:00-04:00 EDT

// Attempt to adjust to Central Time
$new_timezone = new \DateTimeZone('America/Chicago');
$test_date->setTimezone($new_timezone);
// Output 2022-09-27 12:30:00-05:00 CDT

The issue is that under some conditions the default timezone has been improperly set to EDT, and I'm trying to change it to something else (CDT for example). I'm not wanting to adjust it to display the same time, but adjusted to a different time zone. So the end result ought be 13:30:00-05:00 CDT

How do I properly do that?

4
  • 3
    Why not create a new object? new DrupalDateTime('2022-09-27T13:30', 'America/Chicago')
    – 4uk4
    Sep 16, 2022 at 15:25
  • I guess because I was hoping to make a quick adjustment to alter the datetime object being passed into the method. Sep 16, 2022 at 15:59
  • 1
    This is common practice that you instantiate a new value object if you need a different value.
    – 4uk4
    Sep 16, 2022 at 16:06
  • Will do that then - thank you! Sep 16, 2022 at 16:09

1 Answer 1

2

The Druapl DrupalDateTime class is essentially a wrapper / proxy class for the PHP \DateTime class.

This is what is going on. When you do

$test_date = new DrupalDateTime('2022-09-27T13:30');

you are creating an object to represent a distinct point in time. The unix timestamp for this is 1664299800. This is number of seconds since midnight Jan 1, 1970 in London. But, behind the scenes it it set up so that the human readable form shows the local time in New York.

When you do

$test_date->setTimezone($new_timezone);

you are just setting the display time zone to Chicago. The actual timestamp in the object is still 1664299800. Hence, the output you see.

As the comments say, you either need to instantiate the object and pass in the time zone you want to display in, or create a new object.

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.