0

i am changing server time into another time zone using belowcode

 $datetime = new DateTime(2014-02-27 03:03:00);

$la_time = new DateTimeZone('America/New_York');
$datetime->setTimezone($la_time);
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);

its working fine except AM/PM...

correct result is: 02-26-14 10:03 AM but i am getting result as 02-26-14 10:03 PM.

can you please tell me where the problem

krishna
  • 923
  • 3
  • 15
  • 42

2 Answers2

2

The result will always be based on the original timezone setting. If you want to convert to a different timezone, you must initialize the DateTime object after setting the timezone.

Here's a function to make the job easier:

function convertTimezone($date,$from_tz,$to_tz,$format='Y-m-d h:i A') {
    $date = new DateTime($date, new DateTimeZone($from_tz));
    $date->setTimezone(new DateTimeZone($to_tz));
    return $date->format($format);
}

The function could be improved by checking if the supplied timezones are valid.

Example Usage:

echo convertTimezone('2014-02-27 03:03:00','Pacific/Nauru','Pacific/Chatham');

Output:

2014-02-27 04:48 AM

Demo

Community
  • 1
  • 1
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • sorry i am getting still wrong time. correct answer is 2014-02-27 10:03 AM but i am getting 2014-02-27 03:03 AM. – krishna Feb 28 '14 at 06:41
1

Set the timezone when you initialize the DateTime:

$datetime = new DateTime("2014-02-27 03:03:00", new DateTimeZone('America/New_York'));
$dateformat="Y-m-d h:i A";
return $datetime->format($dateformat);

When you set a DateTime, it uses the timezone then in effect. If you change the timezone later, it will change the representation of the time, but the time will be based on the original timezone setting.

EDIT: I didn't read the question carefully enough; you should set the time zone when you initialize the DateTime object, as in the manual.

elixenide
  • 44,308
  • 16
  • 74
  • 100
  • if i placed date after settimezone() i am getting fatal error like "Fatal error: Call to a member function setTimezone() on a non-object" – krishna Feb 28 '14 at 06:47