I'm stucked on javascript. I get thi example string from JSON :
Saturday 14th August
How can i convert it in
14/08/2021
Thanks.
I'm stucked on javascript. I get thi example string from JSON :
Saturday 14th August
How can i convert it in
14/08/2021
Thanks.
You can do it with Pure Javascript
with much more logic. My suggestion is to use Moment.Js It's a really easy way to handle complex DateTime data.
Check this working code:
const dateString = "Saturday 14th August";
const formattedDate = moment(dateString, "dddd Do MMMM").format("DD/MM/Y");
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
NOTE:
As @svarog
mentioned in the comment, It's hard to find the year, If it's not provided. But the common practice is getting the current year. Moment JS handles this very well.
let jsonDateString = "Saturday 14th August"
//this is the string you get
let jsonDateStringArray = jsonDateString.split(" ");
//here we split the words so we can better manipulate them
let month = jsonDateStringArray[2];
//we save the month here
let day = jsonDateStringArray[1].replace(/\D/g, "");
//saving the day and removing everything but numbers
let year = new Date().getFullYear();
//creating a date so we can get the year without having to hardcode it
let completeDate = new Date(Date.parse(month + ' ' + day + ', ' + year));
//create a new date from the string we pass 'August 14, 2021'
console.log(completeDate.toLocaleDateString('en-GB'));
//parameter en-GB for 14/08/21, without parameter we get 08/14/2021