我有一个问题.API的日期会在2016年2月4日回复给我.我必须应用一些日期修改,我需要的日期格式为02-04-2016.该代码适用于从9返回的API返回的日期,例如2016年2月10日,因为当我操纵它时,我得到它整齐地在02-10-2016.然而,问题是日期低于10,例如2016年2月4日,因为这些导致02-4-2016导致错误.
我想知道的是我如何能够始终如一地获得02-04-2016的格式,无论API的日期是9还是10以下.以下是我的代码.
// Split checkin date string from API
list($month, $day, $year, $time) = explode(' ', $checkindate);
// change short month name (e.g Feb) to month number (e.g. 02)
$monthname = $month;
$month = date('m', strtotime($monthname));
// new checkin date in example format 02-20-2016
$checkin_new = $month.'/'.$day.'/'.$year; // this is the part that causes an error when date returned by API is below 10, for example Feb 4 2016. Other dates above 9 such as Feb 10 2016 work well and don't cause an issue.
// Subtract days
$newdate = new DateTime($checkin_new );
$subtracteddate = $newdate->modify("-1 day");
Run Code Online (Sandbox Code Playgroud)
m您可以简单地要求 PHP 立即完成所有工作:
$formatted_date = date('m-d-Y', strtotime($chekindate));
Run Code Online (Sandbox Code Playgroud)