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'...
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():tomorrownext Thursdaylast Mondayfirst day of next month3 days ago+2 weeksnext week TuesdaynowYou can use terms like
tomorrow,next,last, andagoto specify relative dates, and you can combine them with days, weeks, months, or other time units.Example: