Changing a date format in JavaScript

Let's now learn how to change the date format. Let, for example, we have a date string in the format year-month-day. Let's change the format of this date to another, for example, to this one: day/month/year.

Let's solve the problem with a specific example. Let the variable date contain the date '2025-12-31'. Let's convert this date to '31/12/2025'

To solve the problem, let's split our tring '2025-12-31' into an array using the split method with a separator hyphen. As a result, the zero element of the array will contain the year, the first - the month, and the second - the day:

let str = '2025-12-31'; let arr = str.split('-'); console.log(arr); // gets the array ['2025', '12', '31']

Now, referring to different elements of the array by their keys, we will form the string we need:

let str = '2025-12-31'; let arr = str.split('-'); let res = arr[2] + '/' + arr[1] + '/' + arr[0]; console.log(res); // gets the string '31/12/2025'

You can also use a combination of methods split, reverse and join:

let str = '2025-12-31'; let res = str.split('-').reverse().join('/'); console.log(res); // gets the string '31/12/2025'

Given a date in the format year-month-day. Convert this date to the format day.month.year.