Search code examples
javascriptmomentjslocaltime

How to get TimeZone wise local time using moment.js


i am working with two js library to get browser timezone id and browser local time

    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jstimezonedetect/1.0.4/jstz.min.js"></script>
    <script src="Scripts/moment-timezone.min.js" type="text/javascript"></script>


<script type="text/javascript">
        $(document).ready(function () {
            var tz = jstz.determine(); // Determines the time zone of the browser client
            alert(tz.name());

            alert(moment.tz(tz.name()).format());
        });
    </script>

this below code return perfect timezone id

       var tz = jstz.determine(); // Determines the time zone of the browser client
        alert(tz.name());

but this code is not working alert(moment.tz(tz.name()).format()); not giving user local time.

am i missing something in code? do i need to add any momentjs related other file ?

please guide me. i want to get user local time using moment.js. thanks

UPDATE Working Version

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="Scripts/jstz.min.js"></script>

    <script src="Scripts/moment.min.js" type="text/javascript"></script>
    <script src="Scripts/moment-timezone-with-data-2010-2020.min.js" type="text/javascript"></script>
</head>
<body>
    <form method="post" action="WebForm1.aspx" id="form1">
    <div>
    <script type="text/javascript">
        $(document).ready(function () {
            var tz = jstz.determine(); // Determines the time zone of the browser client
            alert(tz.name());

            var format = 'YYYY/MM/DD HH:mm:ss ZZ';
            alert(moment.tz('Europe/London').format(format));
            alert(moment.tz(tz.name()).format(format));
        });
    </script>
    </div>
    </form>
</body>
</html>

Solution

  • My solution of this case (this is part of the page code):

    function toLocalTime(time) {
    	if (time <= 0)
    		return '';
    		
    	var m = moment.tz(time, 'America/Chicago'); //CDT
    	
    	var tz = jstz.determine(); // Determines the time zone of the browser client
    	
    	m.tz(tz.name()); // Convert CDT to local time
    	
    	return m.format('HH:mm:ss');
    }
    <script src="js/jstz.min.js"></script>
    <script src="js/moment.js"></script>
    <script src="js/moment-timezone-with-data-2010-2020.js"></script>
    
    ...........
    
    <script th:inline="javascript">document.write(toLocalTime(<<TIME IN MILLISECONDS HERE>>));</script>