如何修复来自外部源 PHP 的日期不一致



我有一个问题。来自API的日期回到我2016年2月4日。我必须应用一些日期修改,我需要格式为 02-04-2016 的日期。该代码适用于从 API 返回的高于 9 的日期,例如 Feb 10 2016,因为当作它时,我将其整齐地理解为 02-10-2016。但是,问题出在 10 以下的日期上,例如 Feb 4 2016,因为这些日期会导致 02-4-2016 导致错误。

我想知道的是,无论 API 的日期高于 9 或低于 10,我如何始终如一地获得 02-04-2016 的格式。以下是我的代码。

// 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");

要获取二月的日期,请使用mktime函数:

echo date("M d Y ", mktime( 0,0,0,2, 4, 2016));
echo "<br />";
echo gmdate("M d Y ", mktime( 0,0,0,2, 2, 2016));

这将给出输出:

Feb 04 2016
Feb 01 2016

m你可以简单地要求PHP一次完成所有工作:

$formatted_date = date('m-d-Y', strtotime($chekindate));

尝试直接使用函数strtotime

echo date('m-d-Y', strtotime('Feb 4 2016'));

我设法想到了一个解决方案。可能不理想,但它有效。

基本上,问题是当一天低于 10 时,我需要在例如 4 之前添加一个 0。9 以上的日子已经很好用了。所以我写了一个简单的if语句,并在代码中连接了它。更新的部分以粗体显示

// Split checkin  date string from API
list($month, $day, $year, $time) = explode(' ', $checkindate); 
// if day is below 9, give var patchday value 0. Otherwise leave it empty
**if ($day < 10) { $patchday = "0"; } else { $patchday = ""; };**
// 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.'/'.**$patchday**.$day.'/'.$year;
// Subtract days
 $newdate = new DateTime($checkin_new ); 
 $subtracteddate = $newdate->modify("-1 day");

使用可以接受多种格式的日期时间对象

echo (new DateTime('Feb 4 2016'))->format('m-d-Y');
您应该使用

DateTime::createFromFormat 方法,接受月份而不带前导零,三个字母的月份,中间有空格,方法是使用这样的F j Y;

$date = DateTime::createFromFormat('F j Y', $checkindate);

然后格式化它,就像这样;

$formatteddate = $date->format('m-d-Y');

如果时间也是从 API 返回的,那么您只需要以正确的格式(您可以在文档页面上找到)将其添加到您的createFromFormat字符串中,例如 H:i:s ;

$date = DateTime::createFromFormat('F j Y H:i:s', $checkindate);

最新更新