DateTime::format and strftime
Asked Answered
K

3

4

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)?

Karns answered 3/6, 2013 at 22:33 Comment(1)
possible duplicate of #8745452Adversaria
K
23
setlocale(LC_TIME, 'it_IT.UTF-8');
$date = new DateTime($run['at']);
strftime("%d %B", $date->getTimestamp())

... worked. :)

Karns answered 3/6, 2013 at 22:46 Comment(3)
It was easy to find next time before posting a question do some research because this question was easy to be googled.Adversaria
@Adversaria Easy to be googled, yet wrong. getTimstamp() makes the DateTime object lose its timezone. The correct way would be to output the DateTime in any format that strtotime can recognize and then pass that to strftime.Evangelineevangelism
This answer may seem right at first. But getTimstamp() makes the DateTime object lose its timezone. The output will be wrong whenever GMT is in another month than your local timezone. The correct way would be to strip the timezone by outputting the DateTime in any format that strtotime can recognize and then pass that to strftime.Evangelineevangelism
C
0

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
Chronaxie answered 29/11, 2020 at 15:39 Comment(0)
A
-3

I believe the "proper" way should be using DateTimeZone

Alfonzoalford answered 6/8, 2014 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.