在页面上显示日期

问题描述:

my date format from my db was Y-m-d h:i:s sample: 2017-08-30 19:19:20 and im trying to display that date on my page..

but the problem is when it displays on my page the date was different compared to the data from my db..

like data from db was

2017-08-21  18:00:00
2017-08-24  18:00:00
2017-08-30  18:00:00

but the date that was being displayed was

12/31/1969 6:00 PM
12/31/1969 6:00 PM
12/31/1969 6:00 PM

this is the format that i use..

<?php echo date('m/d/Y H:i a',strtotime($date)); ?>

$date is the date from my db..

the date should be 
08/21/2017 6:00 PM
08/24/2017 6:00 PM
08/30/2017 6:00 PM

any idea why this happens and any possible solution for this?..

我的数据库中的日期格式为Ymd h:i:s示例:2017-08-30 19:19: 20,我试图在我的页面上显示该日期.. p>

但问题是,当它显示在我的页面上时,日期与我的数据库中的数据相比有所不同.. p >

像db的 data p>

  2017-08-21 18:00:00 
2017-08-24 18:00:00  n2017-08-30 18:00:00 
  code>  pre> 
 
 

但显示的日期是 p>

  12  / 31/1969 6:00 PM 
12 / 31/1969 6:00 PM 
12 / 31/1969 6:00 PM 
  code>  pre> 
 
 

这是格式 我使用.. p>

 &lt;?php echo date('m / d / YH:i a',strtotime($ date));  ?&gt; 
  code>  pre> 
 
 

$ date是我的数据库中的日期.. p>

 日期应该是
08  / 21/19 PM下午6:00 
08 / 24/2017 6:00 PM 
08 / 30/2017 6:00 PM 
  code>  pre> 
 
 

知道为什么会发生这种情况 和任何可能的解决方案?.. p> div>

The given lines of php code should be able to give the required output :-

<?php

$dates = [
'2017-08-21  18:00:00',
'2017-08-24  18:00:00',
'2017-08-30  18:00:00',
];

foreach ($dates as $string) {
    $date = new DateTime($string);
    echo $date->format('m/d/Y g:i A')."
";
}

Output:

08/21/2017 6:00 PM
08/24/2017 6:00 PM 
08/30/2017 6:00 PM

The code snippet is taken from the 3v4l.org.

The other answers seems to answer how to fix it.
I thought I could explain why it happens.

Strtotime fails because it can't parse the date and returns false.
False is the same as 0.
This zero is taken by date and creates a date according to your format.
But because strtotime returned 0 the date returns 0 UNIX time => 1970-01-01 00:00.
And since you are in a timezone (or server at least) with negative difference to UTC a few hours are subtracted from 1970-01-01 00:00 and that leaves you with your output.