How to convert local date time into gmt using php?

by ryan.murray , in category: PHP General , 2 months ago

How to convert local date time into gmt using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 2 months ago

@ryan.murray 

To convert a local date time into GMT using PHP, you can use the DateTime and DateTimeZone classes. Here is an example code snippet to demonstrate how to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Create a new DateTime object with the local date time
$localDateTime = new DateTime('2022-09-15 14:30:00', new DateTimeZone('America/New_York'));

// Set the timezone to GMT
$gmtTimeZone = new DateTimeZone('GMT');

// Convert the local date time to GMT
$localDateTime->setTimezone($gmtTimeZone);

// Get the GMT date time as a formatted string
$gmtDateTime = $localDateTime->format('Y-m-d H:i:s');

echo $gmtDateTime;


In this code, we first create a new DateTime object with the local date time '2022-09-15 14:30:00' in the 'America/New_York' timezone. Next, we create a new DateTimeZone object for the GMT timezone. We then use the setTimezone() method to convert the local date time to GMT. Finally, we format the GMT date time as a string and print it out.


This code will output the equivalent GMT date time for the provided local date time. You can adjust the local date time and timezone values as needed for your specific requirements.