php 24 小时格式的日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35127109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:21:40  来源:igfitidea点击:

Date and time in 24 hours format

phpmysqldatedatetimedatetime-format

提问by Pathik Vejani

I have a date in this format Fri, 15 Jan 2016 15:14:10 +0800, and I want to display time like this 2016-01-15 15:14:10.

我有一个这种格式的日期Fri, 15 Jan 2016 15:14:10 +0800,我想像这样显示时间2016-01-15 15:14:10

What I tried is:

我试过的是:

$test = 'Fri, 15 Jan 2016 15:14:10 +0800';
$t = date('Y-m-d G:i:s',strtotime($test));
echo $t;

But it is displaying date in this format: 2016-01-15 7:14:10, it should be 2016-01-15 15:14:10.

但它以这种格式显示日期:2016-01-15 7:14:10,它应该是2016-01-15 15:14:10.

How can i do this?

我怎样才能做到这一点?

回答by rdiz

Use Hinstead:

使用H来代替:

$test = 'Fri, 15 Jan 2016 15:14:10 +0800';
$t = date('Y-m-d H:i:s',strtotime($test));
echo $t;

H: 24-hour format of an hour with leading zeros 00 through 23

H:小时的 24 小时格式,前导零为 00 到 23

G should be the same, but without leading zeroes though. I suspect that your PHP is set to a different timezone than +0800. Can you confirm your timezone (date_default_timezone_get())?

G 应该相同,但没有前导零。我怀疑您的 PHP 设置的时区与+0800. 您能确认您的时区 ( date_default_timezone_get()) 吗?

EDIT

编辑

OP confirmed that his timezone was set to UTC, in which case it maskes perfect sense that it shows 7 in the morning, as dateuses PHPs default timezone.

OP 确认他的时区设置为 UTC,在这种情况下,它掩盖了它显示早上 7 点的完美感觉,因为date使用 PHP 的默认时区。

If you want to "inherit" the Timezone, while getting more flexibility, you should switch to DateTime:

如果你想“继承”时区,同时获得更大的灵活性,你应该切换到DateTime

echo (new DateTime($test))->format("Y-m-d H:i:s");