In JSF - Getting the Client's Locale (To Display time in browser's timezone)

后端 未结 6 2113
失恋的感觉
失恋的感觉 2020-12-28 10:03

I\'m writing a webapp in JSF 2.0 that displays Timestamps as part of the information to the user. I would like the user to see the timestamps localized to their location (br

6条回答
  •  孤独总比滥情好
    2020-12-28 10:47

    Succeeded. Here is what I did:

    Added to JSF a hidden input field so I can send JavaScript values to the server:

    
        
            
        
    
    

    Using the plugin above, I ran JavaScript code that retrieved the offset of the browser.

    $(document).ready(function() {
        var timezone = jstz.determine_timezone();
    
        $("#timezone_holder").val(timezone.offset());
        $("#timezone_holder").change();
    });
    

    When the timezone input is changed (initiated from the javascript code above) I run this code in the eventListener:

    String strFromJavaScript = getTimezone();
    HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                    .getRequest();
    Locale browserLocale = request.getLocale();
    TimeZone tz = TimeZone.getTimeZone("GMT" + strFromJavaScript);
    
    // set time zone
    SimpleDateFormat formatter = new SimpleDateFormat("MMM d, yyyy, HH:mm", browserLocale);
    formatter.setTimeZone(tz);
    

    Then, whenever I need to format a date I use the Date Formatter that was created above.

提交回复
热议问题