1

I am pulling the creation date out of an object, and receiving it like this: 2021-04-24T05:48:50.650397026Z

How can I turn it into this?: 24.04.2021, 05:48:50

The current date is stored in firstDate. Only vanilla JS please, any help is appreciated <3

async function getDate(image, tag) {
    return fetch('/registry/v2/' + image + '/manifests/' + tag)
        .then(response => response.json())
        .then(data => JSON.parse(data.history[0].v1Compatibility).created)

const firstDate = await getDate(imageName, tags[0]);
console.log(firstDate); // output is 2021-04-24T05:48:50.650397026Z
TheParam
  • 10,113
  • 4
  • 40
  • 51
  • you can do something like this: `let date = new Date("2021-04-24T05:48:50.650397026Z")` then you can get the day with `date.getDay()` or `date.getMonth()`. Combine it with a "." and you have the date in the format you want – Ma G. Jul 26 '21 at 11:13

3 Answers3

1

You can write a simple utility function like below which will return you formatted date.

function getFormattedDate(date) {
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var year = date.getFullYear();
    var time =  date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return day + "." + month + "." + year + ", " + time ;
}

console.log(getFormattedDate(new Date()))
TheParam
  • 10,113
  • 4
  • 40
  • 51
  • The problem is that I have the dates already, the function you have gives me the current date, no? I tried implementing it in my code, but recieve the error "date.getMonth is not a function" – TraktorJack Jul 26 '21 at 12:19
  • you can pass your string format date in `new Date(yourStringDate)` to above function. – TheParam Jul 28 '21 at 06:38
0

You can use .toLocaleString method.

firstDate.toLocaleString();

Here's a more thorough answer https://stackoverflow.com/a/42863295/1825010

justuff
  • 228
  • 3
  • 10
-2

Recommend to use Dayjs if possible, since you can customize the format as you need. It's a very light-weight date formating package (only 2KB):

dayjs('2021-04-24T05:48:50.650397026Z').format('DD.MM.YYYY, hh:mm:ss');
//24.04.2021, 05:48:50
Leon.Z
  • 37
  • 2