mathias5
mathias5

Reputation: 311

Echo date in a prettier way

I'm not too good with dates in php (or any other language) and would need some help to convert a date's format into something more readable.

The string currently looks like this:

2021-03-31T00:00:00.0000000+02:00

But i would much rather prefer it to be similar to this when echo it:

2021-03-31 00:00:00

I have done some more or less useless stuff with string manipulation, but there must be a better way?

Example:

substr('2021-03-31T00:00:00.0000000+02:00',0,10);

How would one do this?

Upvotes: 0

Views: 100

Answers (2)

XMehdi01
XMehdi01

Reputation: 1

You could also do it with string manipulation by

  1. spliting string (e.g $datetime)with letter T to array by function explode
  2. take first element and store it in a variable $date
  3. take the second element of array and store it in $time (only 8 letters which represent time)
$datetime = '2021-03-31T00:00:00.0000000+02:00';
$date_time = explode('T', $datetime);
$date = $date_time[0];
$time = substr($date_time[1],0,8);
echo $date.' '.$time;//2021-03-31 00:00:00

Upvotes: 0

Kim Hallberg
Kim Hallberg

Reputation: 1265

PHP has pretty extensive DateTime functionality that you can take advantage of, for this example you can use the DateTime class or DateTimeImmutable class.

$date = new DateTime('2021-03-31T00:00:00.0000000+02:00');

echo $date->format('Y-m-d H:i:s'); // 2021-03-31 00:00:00

Upvotes: 4

Related Questions