MultiformeIngegno
MultiformeIngegno

Reputation: 7059

DateTime::format and strftime

I have $date = $run['at']; which gives me 2013-06-03T16:52:24Z (from a JSON input). To transform it to get for example "d M Y, H:i" I use

$date = new DateTime($run['at']);
echo $date->format('d M Y, H:i');

Problem is I need the date in italian. And the only function that supports set_locale is strftime. How can I "wrap" DateTime::format with strftime (or replace, dunno)?

Upvotes: 4

Views: 13212

Answers (3)

zod
zod

Reputation: 487

This is how I solved combining the features of DateTime and strftime().

The first allows us to manage strings with a weird date format, for example "Ymd". The second allows us to translate a date string in some language.

For example we start from a value "20201129", and we want end with an italian readable date, with the name of day and month, also the first letter uppercase: "Domenica 29 novembre 2020".

// for example we start from a variable like this
$yyyymmdd = '20201129';

// set the local time to italian
date_default_timezone_set('Europe/Rome');
setlocale(LC_ALL, 'it_IT.utf8');

// convert the variable $yyyymmdd to a real date with DateTime
$truedate = DateTime::createFromFormat('Ymd', $yyyymmdd);

// check if the result is a date (true) else do nothing
if($truedate){

  // output the date using strftime
  // note the value passed using format->('U'), it is a conversion to timestamp
  echo ucfirst(strftime('%A %d %B %Y', $truedate->format('U')));

}

// final result: Domenica 29 novembre 2020

Upvotes: 0

Nijboer IT
Nijboer IT

Reputation: 1218

I believe the "proper" way should be using DateTimeZone

Upvotes: -3

MultiformeIngegno
MultiformeIngegno

Reputation: 7059

setlocale(LC_TIME, 'it_IT.UTF-8');
$date = new DateTime($run['at']);
strftime("%d %B", $date->getTimestamp())

... worked. :)

Upvotes: 23

Related Questions