Выводим время в различных городах с помощью JavaScript
14:02, 21/03/2018
Реализация функции вывода времени в разных городах по их часовому поясу.
/* Calculate local time in a different cities by [www.m5-web.com] */ function calcTime(city, offset, html_id, display_city) { // create Date object for current location var date = new Date(); // convert to msec, add local time zone offset, get UTC time in msec var utc = date.getTime() + (date.getTimezoneOffset() * 60000); // create new Date object for different city using supplied offset var newDate = new Date(utc + (3600000 * offset)); var hours = newDate.getHours(); var hours = ("0" + hours).slice(-2); var minutes = newDate.getMinutes(); var minutes = minutes < 10 ? minutes = "0" + minutes : minutes; var seconds = newDate.getSeconds(); var seconds = ("0" + seconds).slice(-2); if (display_city === true) { var time_str = "[" + city + "] " + hours + ":" + minutes + ":" + seconds; } else if (display_city === false) { var time_str = hours + ":" + minutes + ":" + seconds; } else { var time_str = "argument display_city must be true or false"; } document.getElementById(html_id).innerHTML = time_str; } setInterval(function() { calcTime('Stavropol', '+3', 'time_stavropol', true) }, 1000); setInterval(function() { calcTime('Moscow', '+3', 'time_moscow', false) }, 1000); setInterval(function() { calcTime('Ekaterinbug', '+5', 'time_ekaterinburg', true) }, 1000); setInterval(function() { calcTime('Dubai', '+4', 'time_dubai', true) }, 1000); setInterval(function() { calcTime('Dubai', '+4', 'time_err', 'some bull sh*t') }, 1000); setInterval(function() { calcTime('Montreal', '-8', 'time_mountreal', true) }, 1000);
See the Pen Calculate time for different cities by DeN (@m5studio) on CodePen.
Комментарии