Moment JS, UTC to Local time and Moment Timezone
by enagu
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.4.1/moment-timezone-with-data-2010-2020.min.js"></script>
UTC<br/>
<div id="divUTC"></div><br/>
Your Local Time with respect to above UTC time<br/>
<div id="divLocal">
</div>
<br/>Thailand date time<br/>
<div id="divThai">
</div>
<br/>America date time<br/>
<div id="divUsa">
<br/>Index time<br/>
<div id="divIndex">
</div>
JavaScript
var getIndexTime = function() {
var date = new Date();
var dateCopy = new Date(date);
var offset = date.getTimezoneOffset() * 60 * 1000;
// Offset to UTC
date.setTime(date.getTime() + offset);
// Set the time to 9am (3am CST)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
// Offset back to local time
date.setTime(date.getTime() - offset);
// If the calculated time is in the future subtract a day
if (date.getTime() > dateCopy.getTime()) {
date.setTime(date.getTime() - (24 * 60 * 60 * 1000));
}
return date.toString();
}
$(function(){
setInterval(function(){
moment.locale("es");
var divUtc = $('#divUTC');
var divLocal = $('#divLocal');
//put UTC time into divUTC
divUtc.text(moment().format('MMM D, YYYY', 'es'));
//get text from divUTC and conver to local timezone
var localTime = moment.utc(divUtc.text()).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
divLocal.text(localTime);
$('#divThai').text(moment.tz('Asia/Bangkok').format('YYYY-MM-DD HH:mm:ss'));
$('#divUsa').text(moment.tz('America/Los_Angeles').format('YYYY-MM-DD HH:mm:ss'));
var localIndex = moment(getIndexTime()).tz('America/Chicago').format('MM/DD/YY ha \\U\\S z');
$('#divIndex').text(localIndex);
},1000);
});