Moment JS, UTC to Local time

by Frank Liu

HTML

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<p id="utcTime"></p>
<p id="localTime"></p>
<p id="anotherLocalTime"></p>

JavaScript

// UTC time
let utcTime = "08:00";
var utcText = moment(utcTime,'HH:mm');
var utcText2 = moment("09:00",'HH:mm');
if(utcText.diff(utcText2, 'minutes')){
console.log(utcText.diff(utcText2, 'minutes'));
} else {
console.log(utcText.diff(utcText2, 'minutes'));
}

// First way 
var localText = moment.utc(utcTime,'HH:mm').utcOffset(moment().utcOffset()).format("HH:mm");

// Another way
var anotherway = moment.utc(utcTime,'HH:mm').local().format("L LT");

// Showing times
$("#utcTime").html(utcText + " (UTC Time)");
$("#localTime").html(localText + " (Local Time)");
$("#anotherLocalTime").html(anotherway + " (Local Time another way)");