I've been able to pull temperatures of a specific city using the WorldTimeAPI:
jQuery.getJSON("https://api.openweathermap.org/data/2.5/weather?q=Rome&units=metric&appid=ab85ba57bbbb423fb62bfb8201126ede", function(data) {
console.log(data);
var temp = Math.floor(data.main.temp);
jQuery(".temp").append(temp + '°C');
});
Now I'm trying to retrieve the date/time in a specific format (14 APR | 14:37)
jQuery.getJSON("http://worldtimeapi.org/api/timezone/Europe/Italy/Rome", function showDateTime() {
var myDiv = document.getElementById("date-time");
var date = new Date();
// var dayList = ["DOM", "LUN", "MAR", "MER", "GIO", "VEN", "SAB"];
var monthNames = [
"GEN",
"FEB",
"MAR",
"APR",
"MAG",
"GIU",
"LUG",
"AGO",
"SET",
"OTT",
"NOV",
"DEC"
];
var dayName = dayList[date.getDay()];
// var monthName = monthNames[date.getMonth()];
var today = `${date.getDate()} ${monthName}`;
var hour = date.getHours();
var min = date.getMinutes();
var time = hour + ":" + min;
myDiv.innerText = `${today} | ${time}`;
}
setInterval(showDateTime, 0);
It pulls the time, and it's in real time, but of my local hour, and not of Rome (location I need to point to, and that I am successfully getting via the API for the temperature.
How can I get the time/date of Rome while connecting from somewhere else? I need to always show the current time/date of Rome and not of the user visiting.
Very appreciated!
The key to making it work is JS's toLocaleString() and related functions. Many (many!) formatting options can be found here.
The OP seemed to have the wrong url for the world time API (Europe/Italy/Rome), but the one used in the snippet (Europe/Rome) produces a reasonable response:
let timer;
let baseTime;
getRomeTime().then(result => baseTime = result);
document.getElementById('start').onclick = () => {
updateTime(0); // edit: start right away
timer = setInterval(updateTime(1000), 1000);
};
document.getElementById('stop').onclick = () => {
clearInterval(timer);
};
function getRomeTime() {
const url = "http://worldtimeapi.org/api/timezone/Europe/Rome"
fetch(url)
.then(r => r.json())
.then(r => {
return new Date(r.datetime);
});
}
// add offset ms to the baseTime and update the DOM
function updateTime(offset) {
baseTime = new Date(baseTime.getTime() + offset);
const localeOptions = {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'full'
};
const timetag = document.getElementById('timetag');
timetag.innerText = d.toLocaleString('it-IT', localeOptions)
}
<p>L'ora è: <span id="timetag"></span></p>
<button id="start">Start</button>
<button id="stop">Stop</button>
Another edit: The time provider might not be intended for frequent invocations. In that case, we can approximate the same result by calling once, then updating the time with the time elapsed as computed on the client.
The snippet below gets Roma time just once, then increments the time by a second every second.
let timer;
let romeTime;
window.onload = () => {
getRomeTime().then(result => {
romeTime = result;
updateTime(0)
timer = setInterval(() => updateTime(1000), 1000);
});
};
function getRomeTime() {
const url = "http://worldtimeapi.org/api/timezone/Europe/Rome"
return fetch(url)
.then(r => r.json())
.then(r => {
return new Date(r.datetime);
});
}
// add offset ms to the baseTime and update the DOM
function updateTime(offset) {
romeTime = new Date(romeTime.getTime() + offset);
const localeOptions = {
timeZone: 'Europe/Rome',
dateStyle: 'full',
timeStyle: 'full'
};
const timetag = document.getElementById('timetag');
timetag.innerText = romeTime.toLocaleString('it-IT', localeOptions)
}
<p>L'ora è: <span id="timetag"></span></p>
According to the documentation,
OpenWeather uses Unix time and the UTC/GMT time zone for all API calls, including current weather, forecast and historical weather data.
Conversion from "UNIX time" to ECMAScript date object has been answered here.
The query in the OP returns data for location:
"lon": -85.1647,
"lat": 34.257
whereas Rome, Italy is at
"lat": 41.9
"lon": 12.483
So you're getting the wrong "Rome". You can change the query to include the country code q=Rome,IT and you'll get data for the expected Rome.
Using the oncall API and the above coordinates or the updated query on 14 April returns sunrise and sunset as:
"sunrise":1649910690,
"sunset":1649958530
which can be converted to local time in Rome (Italy) using:
let opts = {timeZone:'Europe/Rome', timeZoneName:'short', hour12:false};
let sunrise = new Date(1649910690 * 1000).toLocaleString('en-CA', opts)
let sunset = new Date(1649958530 * 1000).toLocaleString('en-CA', opts)
console.log(`Sunrise: ${sunrise}\n` +
`Sunset : ${sunset}`);
If you want to format the date and time in some other format, there are many questions about formatting dates. In this case you might use something like the following:
// Format date as 14 APR | 14:37
function myFormat(loc, date = new Date()) {
let {month, day, hour, minute} = new Intl.DateTimeFormat('en', {
day: 'numeric',
month: 'short',
hour: 'numeric',
minute: '2-digit',
timeZone: loc,
hour12: false
}).formatToParts(date).reduce((acc, part) => {
acc[part.type] = part.value;
return acc;
}, Object.create(null));
return `${day} ${month.toUpperCase()} | ${hour}:${minute}`;
}
// Current local date
console.log(`Current local time: \n${myFormat()}`);
// Date in Rome, Italy for supplied UNIX time value
console.log(`Sunrise for Rome, Italy local time:\n` +
`${myFormat('Europe/Rome', new Date(1649910690 * 1000))}`
);