I have referenced two scripts into my project:
<script src="http://momentjs.com/downloads/moment.js"></script>
<script src="http://momentjs.com/downloads/moment-timezone-with-data.js"></script>
And now the code part:
<script>
$(document).ready(function () {
var now = moment(); // current timestamp, using your machine's time zone
var nowNY = now.tz('America/New_York'); // converted to NY time zone
console.log("Current time in NYC: " + nowNY.format());
});
</script>
In console this displays the following:
Current time in NYC: 2018-12-13T03:59:13-05:00
Now I just need to extract the part with the 03 (hours) 59 (minutes) and 13 (seconds)
But I'm not sure how to do this, can someone help me out?
Simply use format('HH:mm:ss')
This is the most robust display option. It takes a string of tokens and replaces them with their corresponding values.
You can use HH
for 00-24 hours, mm
for 0-59 minutes and ss
for seconds.
Here a live sample:
var now = moment(); // current timestamp, using your machine's time zone var nowNY = now.tz('America/New_York'); // converted to NY time zone console.log("Current time in NYC: " + nowNY.format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Adding to @VincenzoC 's answer (and as he correctly added in his comment ), the moment library has specific Getters for hours, minutes, seconds if you want to use. Like this ( as dictated in the moment docs )
var now = moment(); console.log(now.hours());
Or if you want to stay with the format
function you can use it like this
now.format('HH'); now.format('mm'); now.format('ss');
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.