Is there a list of possible relative date formats I can pass to Carbon::parse() in PHP?

166 Views Asked by At

Carbon::parse() accepts relative date strings, like 'first day of next month'. My team members want to add an input field for this in a VueJS / Laravel application, but I'm concerned about validation.

As it turns out, all of these strings are parsed by Carbon without throwing an error:

  • 'first day of next month'
  • 'first day of next week'
  • 'first day of next year'

However the latter two give incorrect results, provided that the date at time of writing is 2023-10-26:

  • 'first day of next month': 2023-11-01 (correct)
  • 'first day of next week': 2023-09-01 (incorrect)
  • 'first day of next year': 2023-10-01 (incorrect)

How do I know in advance what formats are supported and actually work without giving incorrect results?

I searched the documentation which states:

The string passed to Carbon::parse or to new Carbon can represent a relative time (next sunday, tomorrow, first day of next month, last year) or an absolute time (first day of December 2008, 2017-01-06). You can test if a string will produce a relative or absolute date with Carbon::hasRelativeKeywords().

Are these literally the only possibilities or is there more?

I asked ChatGPT and it knew that 'first day of next year' would not work, but it could not provide me with the source of information. It said something about 'general knowledge'...

1

There are 1 best solutions below

4
engrhussainahmad On

When using Carbon::parse(), you can provide various date formats to parse a date string.

Here are some examples of the relative date formats that you can pass to Carbon::parse():

  1. tomorrow
  2. next Thursday
  3. last Monday
  4. first day of next month
  5. 3 days ago
  6. +2 weeks
  7. next week Tuesday
  8. now

You can use terms like tomorrow, next, last, and ago to specify relative dates, and you can combine them with days, weeks, months, or other time units.

Example:

$date = Carbon::parse('next Wednesday');
echo $date->toDateString(); // Outputs the date of the next Wednesday

Carbon::now()->startOfWeek()->addWeek(); // Output first day of next week