简体   繁体   中英

How To convert UTC into local time on the web with javascript? from http://openweathermap.org/

I am building a weather app using HTML, CSS and JavaScript. I have succeed in displaying my current time but no luck displaying local time of the input city.

here is what it looks like:

在此处输入图片说明

Can I perhaps us getTimeZoneOffset() somewhere? I don't seem to figure out

function displaytheResults (weather) {
let now = new Date();
  let date = document.querySelector('.location .date')
  date.innerText = dateBuilder(now);

}
  function dateBuilder(dt) {
    let months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
    let days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday']
    
    let date = dt.getDate();
    let year = dt.getFullYear();

    let day = days[dt.getDay()];
    let month = months[dt.getMonth()]

    return `${day} ${date} ${month} ${year}`;
}
    

Once you have the offset value, pass it into this function, in order to get the time in the desired city:

function dateBuilder(city, offset) {

    var date = new Date();
    var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
    var newDate = new Date(utc + (3600000 * offset));


    return `The local time in ${city} is ${newDate.toLocaleString()}`
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM