为了账号安全,请及时绑定邮箱和手机立即绑定

碳日期比较和日期格式

碳日期比较和日期格式

PHP
烙印99 2024-01-19 17:06:29
我正在尝试以下操作:我正在开发一个函数来比较以下格式的两个日期:$date = "Mon Sep 14 2020 02:07:25 GMT+0000 (Coordinated Universal Time)";该函数如下(它有一些用于我的测试的额外代码):private function isMoreRecent($newVariation, $oldVariation) {    // dates for testing:    $newVariation = "Mon Sep 14 2020 02:07:25 GMT+0000 (Coordinated Universal Time)";    $oldVariation = "Sun Sep 13 2020 12:02:49 GMT+0000 (Coordinated Universal Time)";    // dates for testing:    // date: 2020-09-14 02:07:25.0 UTC (+00:00)    $newVariationFormat = $this->reformatDate($newVariation);       // date: 2020-09-13 12:02:49.0 UTC (+00:00)    $oldVariationFormat = $this->reformatDate($oldVariation);        if ($newVariationFormat->toDateString() < $oldVariationFormat->toDateString()) {        dd('holaaa');        return true;    }    return false;}“reformatDate”是将字符串日期转换为 Carbon 类型的函数,如下所示:private function reformatDate($date) {    $month = substr($date, 4, 3);    $month = intval($this->getMonthNumber($month));    $day = intval(substr($date, 8, 2));    $year = intval(substr($date, 11, 4));    $hour = substr($date, 16, 2);    $minutes = substr($date, 19, 2);    $seconds = substr($date, 22, 2);    return Carbon::create($year, $month, $day, $hour, $minutes, $seconds);}其中 getMonthNumber():private function getMonthNumber($month) {    $monthKeyValues = [        '1' => 'Jan',        '2' => 'Feb',        '3' => 'Mar',        '4' => 'Apr',        '5' => 'May',        '6' => 'Jun',        '7' => 'Jul',        '8' => 'Ago',        '9' => 'Sep',        '10' => 'Oct',        '11' => 'Nov',        '12' => 'Dec',    ];    return array_search($month, $monthKeyValues);}
查看完整描述

2 回答

?
湖上湖

TA贡献2003条经验 获得超2个赞

最近的日期大于较早的日期。所以你必须改变比较的方向。

为什么不直接比较 Carbon 对象而不是将它们转换为字符串?尝试这个

if ($newVariationFormat->greaterThan($oldVariationFormat))

前面的代码通常应该返回 true;


查看完整回答
反对 回复 2024-01-19
?
LEATH

TA贡献1936条经验 获得超6个赞

Carbon 对象还可以与标准运算符进行比较:

if ($newVariationFormat > $oldVariationFormat)

并且您重新格式化Date可以缩短:

private function reformatDate($date) {
    return Carbon::parse(preg_replace('/\s+\(.*\)$/', '', $date));
}


查看完整回答
反对 回复 2024-01-19
  • 2 回答
  • 0 关注
  • 31 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信