我正在尝试检查一个日期是否等于另一个日期,但是我无法获得匹配,因为来自表单的日期格式一旦通过"就变成了不同的顺序。解析"码。 我需要格式化这个日期以找到匹配项,这是一个示例代码,用于说明我的尝试方式:
...
// $ago will give me this date: 2016-12-09 00:00:00
$ago = Carbon\Carbon::today()->addDays(2); // Todays date + 2 days
//$request->datex has the date coming from a form with this format, '12-06-2016'.
// Once a parse $request->datex here, the date gets out of order:
$my_date = Carbon\Carbon::parse($request->datex);
// it shows the date like this, 2016-09-12 00:00:00 , I need it to be on this format: 2016-12-09 00:00:00
// then I could do this:
if ( $ago$ == $my_date ) {
dd($my_date.' is equal to: '.$ago );
}else{
dd(' Not equal!');
}
...
感谢您的期待!
答案 0 :(得分:1)
更改此行
$my_date = Carbon\Carbon::parse($request->datex);
用这个:
$my_date = Carbon::createFromFormat('m-d-Y', $request->datex)
我们认为您的格式'12-06-2016'
表示DAY-MONTH-YEAR
<强>更新强> 在我的机器上测试了我的解决方案并且它可以正常识别日期: 什么时候
$request->datex = '12-06-2016'
然后
$my_date = \Carbon\Carbon::createFromFormat('m-d-Y', $datex);
给我这样的日期:public 'date' => string '2016-12-06 18:52:09.000000' (length=26)
日期已正确解析。我刚刚假设的事情。这些日期不会与小时,分钟,秒和毫秒相同。要解决这个问题,我们必须通过这种方式比较日期:
if ( $ago->format('Y-m-d') == $my_date->format('Y-m-d') )
//do something awesome with our equal dates