I used the Dark Sky API variable 'time' to retrieve the unix timestamp, then converted it to hour with the following code:
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.latitude;
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}https://api.darksky.net/forecast/7fa728a1a158d84bf2c85bbeb53ddaea/36.778259,-119.417931`;
fetch(api)
.then(response => {
return response.json();
})
.then(data => {
/*console.log(data);*/
const {temperature, summary, icon, time} = data.currently;
//Get date from time variable
var date = new Date(time*1000);
// Get hours from date
var hours = date.getHours();
// Get minutes from date
var minutes = "0" + date.getMinutes();
// Get seconds from date
var seconds = "0" + date.getSeconds();
// Display time in 10:30:23 format
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
console.log(formattedTime);
//Check time
if (hours <= 19 && hours >= 7) {
//Day
} else {
//Night
}
});
Everything else is working perfectly but it's still not displaying the correct time of the retrieved location data in the console.
According to the docs of Dark Sky API :
The API sends a response with a specific format that contains several data, but what's concerns us in this situation is:
timezone (e.g. America/New_York) required
The IANA timezone name for the requested location. This is used for text summaries and for determining when hourly and daily data block objects begin.
Data Point Object
time required
The UNIX time at which this data point begins. minutely data point are always aligned to the top of the minute, hourly data point objects to the top of the hour, and daily data point objects to midnight of the day, all according to the local time zone.
So the time you have read is the machine UNIX time and this type of time is global time it is not for a specific time zone, so if you need displaying the correct time of the retrieved location you need to convert it to Locale Time by using toLocaleTimeString()
in javascript
const proxy = "https://cors-anywhere.herokuapp.com/";
const api = `${proxy}https://api.darksky.net/forecast/7fa728a1a158d84bf2c85bbeb53ddaea/36.778259,-119.417931`;
fetch(api)
.then(response => {
return response.json();
})
.then(data => {
/*console.log(data);*/
const { temperature, summary, icon, time } = data.currently;
//using data.timezone to displaying correct time of the retrieved location
//Get time in 24 00:00:00 format
var formattedTime = new Date(time * 1000).toLocaleTimeString("en-US", { timeZone: data.timezone, hour12: false });
//Get time in 12 00:00:00 AM/PM format
var formattedTime = new Date(time * 1000).toLocaleTimeString("en-US", { timeZone: data.timezone });
console.log(formattedTime);
});
References :