0

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.

PeraDev
  • 27
  • 1
  • 4

2 Answers2

0

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.

BadPiggie
  • 5,471
  • 1
  • 14
  • 28
  • 1
    MomentJS is unmaintained library as of 2021 – Gaël J Aug 11 '21 at 19:48
  • 1
    @GaëlJ—moment.js isn't unmaintained, it's considered "[*a legacy project in maintenance mode*](https://momentjs.com/docs/#/-project-status/)". But yes, it's recommended not to use it for new projects. Also, there are many, many very much smaller date libraries that are good alternatives for parsing and formatting, or a simple 3 line function. – RobG Aug 12 '21 at 00:28
-1

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
  • `new Date(Date.parse(month + ' ' + day + ', ' + year))` is not a good idea, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Aug 12 '21 at 00:24