I'm trying the following:
I'm developing a function to compare two dates in the following format:
$date = "Mon Sep 14 2020 02:07:25 GMT+0000 (Coordinated Universal Time)";
The function is the following (it has some extra code for my tests):
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;
}
The "reformatDate" is a function to convert our string date to a Carbon type as follows:
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);
}
Where 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);
}
it returns an object like this:
Carbon\Carbon @1600049245 {#255 ▼
#constructedObjectId: "0000000021e9258b000000005e04548d"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 [▶]
#dumpLocale: null
date: 2020-09-14 02:07:25.0 UTC (+00:00)
}
Well I have the following question: for the two dates I'm using 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)";
$newVariation is earlier than $oldVariation, so why:
if ($newVariationFormat->toDateString() < $oldVariationFormat->toDateString()) {
dd('holaaa');
return true;
}
return false;
returns me false instead true?
I've been following the Carbon documentation and according to it $newVariationFormat must be less than $oldVariationFormat.
I've also tested using lessThan, $first->lessThan($second), but the same.
What am I doing wrong?
Thanks a lot!!
[EXTRAHELP]: I finally need to transform our dates to the following format:
'2020-08-13T16:09:22.421Z'
What kind of format is it?
Thanks.
createFromFormat
, rather than your unsophisticatedreformatDate
function. – CBroe Sep 14 '20 at 13:45