'Use date-fns formatting style in php using Carbon
I have an app where my users can enter a format string for a date object. I use date-fns to format the dates (with this format) and it works perfectly on the front end:
import { format } from "date-fns";
import { es } from "date-fns/locale";
const formatStr = "yyyy-MM-dd" // user defined
format(date, formatStr, { locale: es }); // returns "2022-03-23"
The problem is that now I have to use the same format in php. I thought Carbon would do the job, but it actually uses php date formatting style.
$formatStr = "yyyy-MM-dd"; // same value as before
Carbon::parse($date)->format($formatStr) // returns "22222222-MarMar-2323"
Is there any way to "translate" date-fns formatting style to Carbon, or should I use another library?
Solution 1:[1]
Carbon has an isoFormat() that accepts a momentjs-style string. From their documentation:
->isoFormat(string $format): string use ISO format rather than PHP-specific format and use inner translations rather than language packages you need to install on every machine where you deploy your application. isoFormat method is compatible with momentjs format method, it means you can use same format strings as you may have used in moment from front-end or node.js. Here are some examples:
$date = Carbon::parse('2018-06-15 17:34:15.984512', 'UTC');
echo $date->isoFormat('MMMM Do YYYY, h:mm:ss a'); // June 15th 2018, 5:34:15 pm
echo "\n";
echo $date->isoFormat('dddd'); // Friday
echo "\n";
echo $date->isoFormat('MMM Do YY'); // Jun 15th 18
echo "\n";
echo $date->isoFormat('YYYY [escaped] YYYY'); // 2018 escaped 2018
So you should be able to use
Carbon::parse($date)->isoFormat($formatStr)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | aynber |
