Search code examples
phplaravelphp-carbon

Parsing "m/Y" Date Format in Laravel Carbon


I'm working on a Laravel project where I need to parse date input provided in the format "m/Y" (e.g., "02/2024"). I'm using Carbon for date manipulation.

Here's the part of my code:

$dateString = $request->d;

if ($dateString && preg_match('/^\d{2}\/\d{4}$/', $dateString)) {
    $date = Carbon::createFromFormat('m/Y', $dateString)->startOfMonth();
} else {
    $date = Carbon::now()->startOfMonth();
}

$formattedDate = $date->format('m/Y');

The issue I'm encountering is that when the input date string is "02/2024", for example, the parsed date ends up being "2023-03-01" instead of "2024-02-01".

I've checked the regular expression and the parsing format, and they both seem correct for the "m/Y" format. Can anyone spot what might be causing this discrepancy and suggest a solution?


Solution

  • When you don't provide the other values (day of the month and time), they are automatically populated by the current date & time values, which are outside the range for February so it automatically skips to the following month.

    You can zero out the other values by using an exclamation mark. This will set the non-provided date & time values to 0 rather than the current values. And so you no longer need ->startOfMonth().

    $dateString = $request->d;
    
    if ($dateString && preg_match('/^\d{2}\/\d{4}$/', $dateString)) {
        $date = Carbon::createFromFormat('!m/Y', $dateString);
    } else {
        $date = Carbon::now()->startOfMonth();
    }
    
    $formattedDate = $date->format('m/Y');