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
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:
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
.
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.