Displaying date/time in user's timezone - on client side

后端 未结 3 764
没有蜡笔的小新
没有蜡笔的小新 2020-12-06 07:31

I have a web application that displays datetime stamps on every page, for example:

December 12, 2009 6:00 pm

I would like to dyn

相关标签:
3条回答
  • 2020-12-06 07:53

    Here is how you could do it with the wonderful "progressive enhancement":

    Output the date where you want it to appear, but be sure to specify its timezone (I use GMT here, but you could use UTC, etc). Then swap it out with the local time on load (Automatically handled by JavaScript if the original timezone is provided).

    <div id="timestamp">December 12, 2009 6:00 pm GMT</div>
    <script type="text/javascript">
        var timestamp = document.getElementById('timestamp'),
            t         = new Date(timestamp.innerHTML),
            hours     = t.getHours(), 
            min       = t.getMinutes() + '', 
            pm        = false,
            months    = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    
        if(hours > 11){
           hours = hours - 12;
           pm = true;
        }
    
        if(hours == 0) hours = 12;
        if(min.length == 1) min = '0' + min;
    
        timestamp.innerHTML = months[t.getMonth()] + ' ' + t.getDate() + ', ' + t.getFullYear() + ' ' + hours + ':' + min + ' ' + (pm ? 'pm' : 'am');
    </script>
    
    0 讨论(0)
  • 2020-12-06 07:58

    We are using ExtJS library, which has functionalities regarding date and time which can help you a lot. As a matter of fact, on my Mozilla Firefox, it displays all dates and times according to the browsers time zone.

    0 讨论(0)
  • 2020-12-06 08:02

    You can use Date.getTimeZoneOffset() to get the local offset from GMT.

    var date = new Date();
    var offset = date.getTimezoneOffset();
    

    From there its a SMOP. Using the Javascript Date object you can call date.toDateString to get a human readable date. If you need it server side, have the Javascript send the offset to your server with a GET or POST.

    Formatting the date is another story. Javascript doesn't provide much built in. You could hack it up yourself, but that way bugs and madness lies. Date formatting is something any good Javascript library should provide. For example, JQuery has Datepicker.formatDate.

    0 讨论(0)
提交回复
热议问题