Java display current time

前端 未结 6 1930
一向
一向 2021-01-02 02:05

I have a code which shows me the current date and time when I run my application

DateFormat dateFormat = new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss\");
Calen         


        
6条回答
  •  無奈伤痛
    2021-01-02 02:57

    You do not mention the technical platform of your user interface, such as Swing, SWT, Vaadin, web, or so on. So I'll not address those specifics. The basic approach here applies to all the UI technologies.

    Two basic ideas:

    • Create an element in your user interface to represent the current moment. Could be a text label or a fancy widget such as an animated clock face.
    • Background thread regularly captures the current moment for an update to the display of that UI element. Be careful in how the background thread reaches into the UI thread. Use the appropriate UI technique to communicate the new date-time value and cause the UI widget to update.

    Executor

    For Swing, the Swing Timer may be appropriate (not sure of current status of that technology). But otherwise, learn how to use a ScheduledExecutorService to have a separate thread repeatedly capture the current moment. Search Stack Overflow to learn much more about that Executor.

    java.time

    Use the Instant class to capture the current moment on the timeline in UTC with a resolution up to nanoseconds.

    Instant now = Instant.now();
    

    Pass that object to the UI thread.

    On the UI thread, apply the user’s desired/expected time zone ZoneId to produce a ZonedDateTime.

    ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
    ZobedDateTime zdt = instant.atZone( z ) ;
    

    If you need a String to represent that date-time call toString or use DateTimeFormatter. Notice the ofLocalized… methods on DateTimeFormatter.

    Search Stack Overflow for many hundreds of related Questions and Answers for more details.

提交回复
热议问题