I have one date, I would like to take month and year to this date in Typescript.
For example:
If I have lun. 1 juil. 2024, my code must be return juil 2024.
Can you help me please?
You can use a map for the months, then use Date()
and toLocaleDateString()
:
const months: { [key: string]: string } = {
"juil.": "Jul", // map your month like this
};
function getDate(dt: string): string {
const D = dt.split(" ");
const day = D[1];
const month = months[D[2]];
const year = D[3];
const date = new Date(`${month} ${day} ${year}`);
const options: Intl.DateTimeFormatOptions = {
month: "short",
year: "numeric",
};
const dfr = date.toLocaleDateString("fr-FR", options);
const [m, y] = dfr.split(" ");
return `${m.replace(".", "")} ${y}`;
}
console.log(getDate("lun. 1 juil. 2024"));
juil 2024
Or you can use a pattern to match it:
function matchDate(dt: string): string {
const match = dt.match(/(\w+)\.?\s+(\d{4})/);
return match ? `${match[1]} ${match[2]}` : "";
}
console.log(matchDate("lun. 1 juil. 2024"));
juil 2024