Home > Mobile >  Wrong Date output when inserting timestamp in Date Object (JavaScript)
Wrong Date output when inserting timestamp in Date Object (JavaScript)

Time:09-21

I am trying to use data from the https://www.cryptocompare.com/ api. Weard thing is, when I want to create a new Date Object with that timestamp, I get Tue Jan 20 1970 07:09:15 GMT 0100 (Mitteleuropäische Normalzeit) back. The timestamp is right tho, i checked that on https://timestampgenerator.com/date-from-timestamp.

requestLatestNews();
    function requestLatestNews() {
        fetch(`https://min-api.cryptocompare.com/data/v2/news/?lang=EN&api_key=<key>`)
            .then((response) => {
                console.log(response);
                return response.json();
            })
            .then((data) => {
                console.log(data);
                return data;
            })
            .then((data) => {
                for (let i = 0; i < data.Data.length; i  ) {
                    let publishDate = new Date(data.Data[i].published_on); // Falsche Berechnung
                    console.log(publishDate);
                    let dmy = publishDate.getUTCDate()   "/"   (publishDate.getUTCMonth()   1)   "/"   publishDate.getUTCFullYear();
                    let hms = publishDate.getUTCHours()   ":"   publishDate.getUTCMinutes()   ":"   publishDate.getUTCSeconds();
                    document.querySelector('#output').innerHTML
                         = `<p> <a href="${data.Data[i].guid}">${data.Data[i].source}</a> - ${data.Data[i].title}, ${dmy} ${hms}</p>
                    <img src="${data.Data[i].imageurl}"></img> <p> [${data.Data[i].tags} ${data.Data[i].categories}] </p>
                    <p> ${data.Data[i].body} </p>`;
                }
            })
            .catch((error) => {
                console.log('Error Code: '   error);
            });
    }

CodePudding user response:

I think you should take a look at the Date contructor for JavaScript: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date

Quoting from the documentation:

Time value or timestamp number - value

An integer value representing the number of milliseconds since January 1, 1970, 00:00:00 UTC (the ECMAScript epoch, equivalent to the UNIX epoch), with leap seconds ignored. Keep in mind that most UNIX Timestamp functions are only accurate to the nearest second.

You can try out the value you receive on that page as well.

  • Related