danharrin/date-format-converter
Convert date format strings between PHP, Moment.js, and other common tokens. Handy for keeping Laravel backends and JavaScript frontends in sync when parsing, formatting, or validating dates across different libraries and locales.
1st, 2nd, 3rd, 4th) for day formatting, aligning with libraries like day.js and moment.js. This expands its utility for:
Do for "1st"), requiring explicit use in format strings.Do, D) enable more natural date displays without coupling to Carbon or Intl."1º" vs. English "1st").Do MMMM YYYY → "1st January 2023")."1." in German)."11th", "12th", "13th") are handled, but non-standard formats (e.g., "1º") require explicit configuration.Do is deprecated).switch($day) { case 1: return "1st"; ... }) in your codebase?Do token align with your existing date format conventions (e.g., Carbon, moment.js)?Str::of() + Carbon or IntlDateFormatter achieve this with less overhead?@php echo DateHelper::convert(now()->format('j'), 'D', 'Do') @endphp)."date": "1st January 2023").// Before
$day = $date->day;
$suffix = ($day % 10 === 1 && $day !== 11) ? 'st' : ($day % 10 === 2 && $day !== 12) ? 'nd' : ($day % 10 === 3 && $day !== 13) ? 'rd' : 'th';
echo "$day$suffix";
// After
echo DateHelper::convert($date->format('D'), 'D', 'Do'); // "1st"
// app/Helpers/DateHelper.php
class DateHelper {
public static function formatWithOrdinal(string $date, string $format = 'Do MMMM YYYY'): string
{
return self::convert($date, 'Y-m-d', $format);
}
}
// app/Http/Middleware/FormatOrdinalDates.php
public function handle($request, Closure $next) {
$response = $next($request);
$response->data['formatted_date'] = DateHelper::formatWithOrdinal($response->data['date']);
return $response;
}
DB::raw("DATE_FORMAT(date_column, '%W, %M %D %Y')") → converted to Do tokens).application/json with Do tokens)."Order Date (Do MMMM YYYY)").Do token syntax changes in future versions.composer.json to avoid unexpected token changes.D instead of Do)."1st" vs. "1.").| Scenario | Impact | Mitigation |
|---|---|---|
| Invalid ordinal token | Silent failure or incorrect output | Validate tokens (e.g., assert(str_contains($format, 'Do'))). |
| Locale-specific ordinals | Broken formatting (e.g., "1st" in German) |
Use IntlDateFormatter for locales or document custom tokens. |
| Token syntax changes | Breaking changes in future versions | Pin version in composer.json. |
| Day 11–13 edge cases | Incorrect suffixes (e.g., "11th" → "11st") |
Test thoroughly; add unit tests. |
Do, D) and their use cases.Do vs. D).How can I help you explore Laravel packages today?