【问题标题】:DateTime::format and strftimeDateTime::format 和 strftime
【发布时间】:2013-05-30 04:56:27
【问题描述】:

我有 $date = $run['at'];,它给了我 2013-06-03T16:52:24Z(来自 JSON 输入)。 要将其转换为例如“d M Y, H:i”,我使用

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

问题是我需要意大利语的日期。而唯一支持set_locale的函数是strftime。 我怎样才能用strftime“包装”DateTime::format(或替换,不知道)?

【问题讨论】:

标签: php datetime time datetime-format strftime


【解决方案1】:
setlocale(LC_TIME, 'it_IT.UTF-8');
$date = new DateTime($run['at']);
strftime("%d %B", $date->getTimestamp())

... 工作。 :)

【讨论】:

  • 下次发布问题之前很容易找到做一些研究,因为这个问题很容易被谷歌搜索。
  • @Robert 很容易被谷歌搜索,但错误。 getTimstamp() 使 DateTime 对象失去其时区。正确的方法是以 strtotime 可以识别的任何格式输出 DateTime,然后将其传递给 strftime。
  • 这个答案乍一看似乎是对的。但是 getTimstamp() 会使 DateTime 对象失去其时区。每当 GMT 与您当地时区相差一个月时,输出就会出错。正确的方法是通过以 strtotime 可以识别的任何格式输出 DateTime 来剥离时区,然后将其传递给 strftime。
【解决方案2】:

这就是我结合 DateTimestrftime() 的功能解决的方法。

第一个允许我们管理具有奇怪日期格式的字符串,例如“Ymd”。 第二个允许我们将日期字符串翻译成某种语言。

例如,我们从一个值“20201129”开始,我们希望以一个可读的意大利日期结束,日期和月份的名称,也是第一个大写字母:“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

【讨论】:

    【解决方案3】:

    我相信“正确”的方式应该是使用DateTimeZone

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2023-04-11
      • 2012-05-22
      • 2023-03-18
      • 1970-01-01
      • 2017-06-15
      • 1970-01-01
      相关资源
      最近更新 更多