You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PrimeFaces Clock组件获取UTC格式的日期时间?

问题:PrimeFaces Clock组件切换时区后无法正确显示对应时间

我尝试使用PrimeFaces Clock组件获取UTC格式的当前日期时间,但切换多个时区后始终得到相同结果。示例代码如下:

<p:clock pattern="HH:mm" mode="server" timeZone="Europe/Warsaw"></p:clock>

该问题与Stack Overflow上的相关问题情况一致,但我认为其解决方案并不合适。我已自行实现了一个DateTime生成器,能正常运行,但我的应用是单页应用(SPA),希望头部的当前日期时间字段能自动更新。我可以使用Ajax请求,但更希望直接使用PrimeFaces Clock组件完成需求。自行实现的代码如下:

import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Timer;
import java.util.TimerTask;

@ManagedBean(name = "utcClockBean")
@ApplicationScoped
@ViewScoped
public class UTCClockBean implements Serializable {

    private static final long serialVersionUID = 1L;
    private String currentTime;
    
    public UTCClockBean() {
    }

    @PostConstruct
    public void init() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                currentTime = LocalDateTime.now(ZoneOffset.UTC).format(formatter);
            }
        };

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(task, 0, 1000);
    }

    public String getCurrentTime() {
        return currentTime;
    }
    
    public void setCurrentTime(String currentTime) {
        this.currentTime = currentTime;
    }
}

内容的提问来源于stack exchange,提问作者Eduardo Roque

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 14:56:25