格式化动态时间戳

时间:2018-09-22 05:36:50

标签: php regex

我在PHP中有一个来自json的动态变量

$timestamp = $array['timestamp'];

时间戳显示为:

2018-09-22T05:28:45.676899Z

但是我希望它显示为:

2018-09-22 - 05:28:45

我不知道该怎么做,时间戳是动态的,每分钟都会改变

3 个答案:

答案 0 :(得分:0)

将时间戳转换为DateTime对象,然后可以使用format方法以您喜欢的任何形式将其打印出来。在您的特定情况下:

$timestamp = '2018-09-22T05:28:45.676899Z';
$date = new DateTime($timestamp);
echo $date->format('Y-m-d - H:i:s');

输出:

2018-09-22 - 05:28:45

答案 1 :(得分:0)

使用preg_replace的一个选项:

$input = "2018-09-22T05:28:45.676899Z";
$output = preg_replace("/(\d{4}-\d{2}-\d{2})[T\s]?(\d{2}:\d{2}:\d{2}).*/", "$1 - $2", $input);
echo $input ."\n" . $output;

2018-09-22T05:28:45.676899Z
2018-09-22 - 05:28:45

Demo

答案 2 :(得分:0)

echo date("Y-m-d - H:i:s", strtotime("2018-09-22T05:28:45.676899Z"));

输出

2018-09-21 - 22:28:45
相关问题