Search code examples
javaprimefacesjavabeans

How to get datetime in UTC format using Primefaces clock component?


I am trying to use PrimeFaces clock component and get the current datetime in UTC format. However, I have tried several time zones and always date the same value.

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

This question is the same that Primefaces Clock component is not working as per the timezone attribute value, but I consider its answer is not a right solution.

I have tried creating my own DateTimeGenerator and it works, however my app is a SPA and I would like the current datetime field be always shown in the header, and it change automatically. I could use ajax requests, but I think it would be great if I could use Primefaces Clock component instead:

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
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;
    }
}

Solution

  • import javax.annotation.PostConstruct;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.ViewScoped;
    import java.io.Serializable;
    import java.time.LocalDateTime;
    import java.time.ZoneOffset;
    
    @ManagedBean(name = "utcClockBean")
    @ViewScoped
    public class UTCClockBean  implements Serializable {
    
        private static final long serialVersionUID = 1L;
        private LocalDateTime currentTime;
        
        public UTCClockBean() {
        }
    
        @PostConstruct
        public void init() {
            currentTime = LocalDateTime.now(ZoneOffset.UTC);
        }
    
        public LocalDateTime getCurrentTime() {
            return currentTime;
        }
        
        public void setCurrentTime(LocalDateTime currentTime) {
            this.currentTime = currentTime;
        }
    }
    
    <p:clock mode="server" pattern="HH:mm" value="#{utcClockBean.currentTime}"/>