Home > Mobile >  Display time of specific location
Display time of specific location

Time:04-15

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!

CodePudding user response:

They 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:

const localeOptions = {
  timeZone: 'Europe/Rome',
  dateStyle: 'full',
  timeStyle: 'full'
};

const url = "http://worldtimeapi.org/api/timezone/Europe/Rome"
fetch(url)
  .then(r => r.json())
  .then(r => {
    const d = new Date(r.datetime);
    const inRoma = d.toLocaleString('it-IT', localeOptions)
    console.log(inRoma);
  });

Note in the docs that the locale functions are relatively new in JS, and IE support is limited.

CodePudding user response:

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 in Italy is at

"lat": 41.9
"lon": 12.483 

So you're getting the wrong "Rome". Using the oncall API and the above coordinates 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(myFormat());
// Date in Rome, Italy for supplied UNIX time value
console.log(myFormat('Europe/Rome', new Date(1649910690 * 1000)));

  • Related