user45 user45 - 4 years ago 128
Javascript Question

How to convert date into another format in JavaScript?

I'm getting a date from an API as

2017-04-20T07:00:00Z


How could I format it into the following?

20.04.2017


I'm using React to display the date:

<div>{props.data.day}</div>


I tried for example toISOString().slice(0, 10); but couldn't get that to work properly. I also tried looking at other answers, but couldn't find a solution yet.

Answer Source

The following should work without any third party libraries:

console.log(convertDate(new Date("2017-04-20T07:00:00Z")));

function convertDate(date) {
    var day = date.getDate();
    day = day < 10 ? "0" + day : day;
    var month = date.getMonth() + 1;
    month = month < 10 ? "0" + month : month;
    var year = date.getFullYear();
    return day + "." + month + "." + year;
}

This gives:

20.04.2017

You would need to add this to your component as a function and place the return value as the content of your div.

Please note, as noted in other answers, you are better off using a third party library that can deal with timezones and other time-based problems without you having to think about it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download