Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to convert a date from "DD-MM-YYYY" format to "D MonthName YYYY" format, and viceversa - where "MonthName" is in French.

The first task is quite easy:
JavaScript
var str = "02-04-2023";
[day, month, year] = str.match(/\d+/g);
var dt = new Date(year, month - 1, day).toLocaleDateString("fr-FR", {
day: "numeric",
month: "long",
year: "numeric"
})
console.log(dt); // => 2 avril 2023

But how to do the opposite (in Vanilla JavaScript)? I.e.: how to get "02-04-2023" from "2 avril 2023"?

I don't want to use any array/object of months.

Any suggestions would be much appreciated.

What I have tried:

JavaScript
var str = "02-04-2023";
[day, month, year] = str.match(/\d+/g);
var dt = new Date(year, month - 1, day).toLocaleDateString("fr-FR", {
day: "numeric",
month: "long",
year: "numeric"
})
console.log(dt); // => 2 avril 2023


(But maybe there's a better solution for this)
Posted
Updated 2-Apr-23 5:53am
v2
Comments
0x01AA 2-Apr-23 11:51am    
const frenchDate = "2 avril 2023";
const dateObj = new Date(frenchDate);

// Get day, month, and year values from the date object
const day = dateObj.getDate().toString().padStart(2, '0');
const month = (dateObj.getMonth() + 1).toString().padStart(2, '0'); // Note that month value starts from 0
const year = dateObj.getFullYear();

// Combine day, month, and year values into the desired format
const formattedDate = `${day}-${month}-${year}`;

Anyway a bad approach. Try to stay on formal date/time.
LB2371 2-Apr-23 12:33pm    
It doesn't work:
console.log(formattedDate); // => NaN-NaN-NaN
It works perfectly with "2 April 2023":
console.log(formattedDate); // => 02-04-2023
But I need to use French months.
0x01AA 2-Apr-23 12:45pm    
I see...
const { parse, format } = require('date-fns');
const frenchDate = "2 avril 2023";
const parsedDate = parse(frenchDate, "d MMMM yyyy", new Date(), { locale: require('date-fns/locale/fr') });
const formattedDate = format(parsedDate, 'dd-MM-yyyy');
console.log(formattedDate); // Output: 02-04-2023


Btw. use correct reply button ;)

1 solution

My computer isn't set up for French, but ... give Date.parse() - JavaScript | MDN[^] a try. It works with '2 April 2023' for me, so there is a good chance it'll accept French months on a French configured browser.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900