Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Mostrar la hora de una ubicación específica

Pude obtener temperaturas de una ciudad específica usando 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'); });

Ahora estoy tratando de recuperar la fecha/hora en un formato específico (14 ABR | 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);

Extrae el tiempo, y es en tiempo real, pero de mi hora local, y no de Roma (ubicación a la que debo señalar, y que estoy obteniendo con éxito a través de la API para la temperatura.

¿Cómo puedo obtener la hora/fecha de Roma mientras me conecto desde otro lugar? Siempre necesito mostrar la hora/fecha actual de Roma y no la del usuario que visita.

¡Muy apreciado!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

La clave para que funcione es toLocaleString () de JS y funciones relacionadas. Muchas (¡muchas!) opciones de formato se pueden encontrar aquí .

El OP parecía tener la URL incorrecta para la API de hora mundial ( Europe/Italy/Rome ), pero la utilizada en el fragmento ( Europe/Rome ) produce una respuesta razonable:

 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>

Otra edición: es posible que el proveedor de tiempo no esté diseñado para invocaciones frecuentes. En ese caso, podemos aproximarnos al mismo resultado llamando una vez y luego actualizando el tiempo con el tiempo transcurrido calculado en el cliente.

El fragmento a continuación obtiene el tiempo de Roma solo una vez, luego incrementa el tiempo en un segundo cada segundo.

 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>

about 4 years ago · Juan Pablo Isaza Report

0

Según la documentación ,

OpenWeather utiliza la hora de Unix y la zona horaria UTC/GMT para todas las llamadas a la API, incluido el clima actual, el pronóstico y los datos meteorológicos históricos.

La conversión de "tiempo UNIX" a objeto de fecha ECMAScript se ha respondido aquí .

La consulta en el OP devuelve datos para la ubicación:

 "lon": -85.1647, "lat": 34.257

mientras que Roma, Italia está en

 "lat": 41.9 "lon": 12.483

Así que te estás equivocando de "Roma". Puede cambiar la consulta para incluir el código de país q=Rome,IT y obtendrá datos para la Roma esperada .

El uso de la API de guardia y las coordenadas anteriores o la consulta actualizada el 14 de abril devuelve el amanecer y el atardecer como:

 "sunrise":1649910690, "sunset":1649958530

que se puede convertir a la hora local en Roma (Italia) usando:

 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}`);

Si desea formatear la fecha y la hora en algún otro formato, hay muchas preguntas sobre el formato de las fechas . En este caso, podría usar algo como lo siguiente:

 // 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))}` );

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!