【问题标题】:Date format of json php [duplicate]json php的日期格式[重复]
【发布时间】:2018-05-22 00:07:42
【问题描述】:

我需要将日期时间格式化为更易读的格式,例如:- '23rd September 2018 17.00'

//Json Array

instances": [
{
"start": "2017-08-02T14:15:00"
}
]

//CODE
$count = count($characters->instances);
for(reset($i); $i < $count; ++$i) {
print_r ($characters->instances[$i]->start);
}

【问题讨论】:

标签: php json date datetime


【解决方案1】:

相反,我使用了“方括号”表示法和echo,而不是与strtotime 一起使用的print_r,只需将json_decode 调整为true

成功了!

最终工作代码

$characters = json_decode($data, true);

echo (date('jS  F Y h:i', strtotime($characters['instances'][$i]['start'])));

【讨论】:

    【解决方案2】:

    首先,让我们将 JSON 转换为数组。

    // The 'true' parameter will convert your
    // json to an array instead of an object
    $characters = json_decode($json, true);
    

    现在,让我们遍历您的数组以查找和替换日期。

    foreach ($characters['instances'] as $instanceKey => $instance) {
        foreach ($instance as $key => $value) {
            // Add all keys you'd like to change to the below array
            if (in_array($key, ['start', 'end', 'date'])) {
                $oDate = DateTime::createFromFormat('Y-m-dTH:i:s', $value);
    
                // You can adjust the date format to any format you wish
                // in the below format() portion
                $characters['instances'][$instanceKey][$key] = $oDate->format('jS  F Y h:i');
            }
        }
    }
    

    现在,让我们把它转回 JSON 字符串:

    $json = json_encode($characters);
    

    我可能猜错了您的 JSON 结构。但我认为这只是一个微小的调整。有任何问题,当然可以发表评论。

    【讨论】:

      【解决方案3】:

      你可以在php中使用函数date()

      print_r (date('jS  F Y h:i', strtotime("2017-08-02T14:15:00")));
      

      【讨论】:

      • 这正是副本中的答案。
      • 谢谢,这为我指明了正确的方向并帮助我解决了这个问题
      猜你喜欢
      • 2016-09-23
      • 2014-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2012-05-09
      相关资源
      最近更新 更多