matin
matin

Reputation: 313

Convert Date and Time to other Date and Time with PHP

I am getting date in format 2019-11-26T16:30:00+01:00 from an API and want to convert it to a format like Di. 26. Nov. 2019 / 16:30.

I am usinig following code, but always get 1 hour difference: Di. 26. Nov. 2019 / 15:30 Uhr.

If I use 2019-11-26T16:30:00+02:00 - I get Di. 26. Nov. 2019 / 14:30 Uhr (2 hours earlier).

Here is my php code:

$timstp = strtotime('2019-11-26T16:30:00+1:00');
echo date('d.m.Y H:i:s', $timstp);

How can I get correct date?

Upvotes: 0

Views: 160

Answers (2)

jspit
jspit

Reputation: 7683

Use the DateTime class. The format method returns the result in English.

$input = '2019-11-26T16:30:00+1:00';
$date = date_create($input)->format('D. d. M. Y /H:i \U\h\r');
echo $date;  //Tue. 26. Nov. 2019 /16:30 Uhr

For an output in other languages ​​like German I recommend the DateTime extension class dt.

$input = '2019-11-26T16:30:00+1:00';
$date = dt::create($input)->formatL('D d. M Y / H:i \U\h\r','de_DE');
echo $date; //Di. 26. Nov. 2019 / 16:30 Uhr

Update:

Does the API get entries from different time zones? If so, is the question what is needed? The local time of the time zone or a unique time base for comparability? The examples above show the local time of the time zone. To create a uniquet basis, the DateTime object can be converted to a different time zone how UTC.

$input = '2019-11-26T15:30:00+5:00';
$date = date_create($input)
  ->setTimeZone(new DateTimeZone('UTC'))
  ->format('D. d. M. Y / H:i:s')
;
echo $date;  //Tue. 26. Nov. 2019 / 10:30:00

Upvotes: 1

Umer Abbas
Umer Abbas

Reputation: 1876

try this

$datetime = new DateTime('2019-11-26T16:30:00+1:00');
echo $datetime->format('d.m.Y H:i:s');

find more details about DateTime here

Upvotes: 0

Related Questions