在PHP中将api返回日期时间字符串从24格式转换为12小时格式

问题描述:

I have a datetime like below

17/05/2018 23:59:00 PM

It is storing in database like varchar(100). I want to convert this as 17/05/2018 11:59:00 PM. It is returning from the api.I have tried to fix tried so many ways. somehow it is working but coming tomorrow date like it is giving now like this

18/05/2018 11:59 AM

.Is any efficient way to do this.

 $startdate='17/05/2018 23:59:00 PM';
$myDateTime = DateTime::createFromFormat('d/m/Y H:i A',$startdate);
$newDateString = $myDateTime->format('d/m/Y h:i A');
echo $newDateString;

我的日期时间如下 p>

  17/05 /  2018 23:59:00 PM 
  code>  pre> 
 
 

它存储在数据库中,如varchar(100)。 我想将其转换为17/05/2018 11:59 下午00点。 它正在从api返回。我试图修复尝试了很多方法。 somehow它正在工作,但明天就会像现在这样给出这样的 p>

18 / 05/2018 11:59 AM p>

。这是一种有效的方法。 p>

  $ startdate = '17 / 05 /  2018 23:59:00 PM'; 
 $ myDateTime = DateTime :: createFromFormat('d / m / YH:i A',$ startdate); 
 $ newDateString = $ myDateTime-> format('d / m  / Y h:我是'); 
echo $ newDateString; 
  code>  pre> 
  div>

You are using AM/PM and 24 hour format. That doesn't make sense. PHP is probably trying its best to make sense of it and adding 12 hours to the datetime pushing it to the next day.

If you ignore the PM from your datetime this works just fine:

$startdate='17/05/2018 23:59:00 PM';
$myDateTime = DateTime::createFromFormat('d/m/Y H:i:s+',$startdate);
$newDateString = $myDateTime->format('d/m/Y h:i:s A');
echo $newDateString;

Demo

I would save the timestamp to the dB rather than the actual date

$startDateTime = DateTime::createFromFormat('d/m/Y H:i:s', '17/05/2018 23:59:00');
$timeStamp = $startDateTime->getTimeStamp();

$date = new DateTime();
$date->setTimestamp($timeStamp);

echo $date->format('d/m/Y h:i:s A');