-1

I am receiving a JSON object from a the DarkShy weather api, and I want to access the timestamp for each report for a Chart.JS chart where I will display the temperature over day, right now I am stuck in converting the timestamp into a HH:DD:SS format.

This is what I tried

// Displays the wrong time according to https://www.epochconverter.com/
var timeofDay = new Date(daily[i].time)
time.push( timeofDay.toTimeString().split(' ')[0] )

// Gets rid off the time, tho It get the date correctly
var timeofDay = new Date(parseFloat(daily[i].time) * 1000)
time.push( timeofDay )

// Returns the wrong date and time
time.push(new Date(daily[i]))

Here's how I loop through the JSON file

let time = []
let temperatureDaily = []

for(var i=0; i<daily.length; i++){
 // Push the values into the arrays
 var timeofDay = new Date(parseFloat(daily[i].time) * 1000)
                        time.push( timeofDay )

 temperatureDaily.push( (parseFloat(daily[i].temperatureHigh) + parseFloat(daily[i].temperatureLow)) /2)
}
console.log(time);
Jeremy
  • 1,447
  • 20
  • 40
  • Is there a problem with using [`timeofDay.getHours()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours) and [`timeofDay.getMinutes()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getMinutes)? – Phil Sep 25 '19 at 04:25
  • 1
    What is the value of `daily[i].time`? – RobG Sep 25 '19 at 04:28
  • timeofDay.getHours() is giving me the wrong hours, it should be around 6AM acording to https://www.epochconverter.com/ . Here's the time stamp: 1569304800 and the returned value was: 21 – Jeremy Sep 25 '19 at 04:33
  • Check this out https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript?rq=1 – Ravi Makwana Sep 25 '19 at 04:34
  • 1
    You need to get the UTCHours: `new Date(1569304800 * 1000).getUTCHours()` is `6`. What you're getting is the local hours based on the host timezone offset. – RobG Sep 25 '19 at 04:35
  • ` daily[i].time `, here daily is a var where a store the Daily record for the weather report, and I'm accessing the time key. – Jeremy Sep 25 '19 at 04:35
  • Oh, and you don't need *parseFloat*: `new Date(daily[i].time * 1000)` is sufficient. – RobG Sep 25 '19 at 04:37

2 Answers2

1

If you're only interested in the time, and it seems you want UTC, use UTC methods to format the time. Or you can use toISOString and trim the bits you don't want, e.g.

let timeValue = 1569304800;
let d = new Date(timeValue * 1000);

// Use toISOString
let hms = d.toISOString().substr(11,8);
console.log(hms);

// Manual format
function toHMS(date){
  let z = n => ('0'+n).slice(-2);
  return `${z(d.getUTCHours())}:${z(d.getUTCMinutes())}:${z(d.getUTCSeconds())}`
}
console.log(toHMS(d));
RobG
  • 142,382
  • 31
  • 172
  • 209
-2

Try moment.js.

It gives a lot of date utilities and formatting becomes super easy.

Vishal Sharma
  • 316
  • 1
  • 8