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
How about using a timer, such as javax.swing.Timer? (Do not make mistake in the import, there are more Timer classes.)
public static void main(String... args) throws InterruptedException {
final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
int interval = 1000; // 1000 ms
new Timer(interval, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
System.out.println(dateFormat.format(now.getTime()));
}
}).start();
Thread.currentThread().join();
}
This will simply execute the body of the ActionListener every second, printing the current time.
The Thread.join
call on the last line is not universally necessary, it's just needed for this example piece of code to run until the process is manually stopped. Otherwise, it would immediately stop.
In a real application, in case it's a Swing app, then the timer should handle threading by itself, so you won't have to worry about it.
Integrating the above sample into your application is fairly simple, just add it into the initGUI
method and instead of printing the current time to System.out set change the text of the given label:
public void initGUI() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(800, 600));
setLayout(null);
Calendar now = Calendar.getInstance();
tijd = new JLabel(dateFormat.format(now.getTime()));
tijd.setBounds(100, 100, 125, 125);
window.add(tijd);
new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Calendar now = Calendar.getInstance();
tijd.setText(dateFormat.format(now.getTime()));
}
}).start();
pack();
}
You can try this,
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import java.lang.Thread;
public class TimeInSeconds extends Frame implements Runnable
{
private Label lblOne;
private Date dd;
private Thread th;
public TimeInSeconds()
{
setTitle("Current time");
setSize(200,150);
setVisible(true);
setLayout(new FlowLayout());
addWindowListener(new WindowAdapter() {
public void windowClose(WindowEvent we){
System.exit(0);
}
});
lblOne = new Label("00:00:00");
add(lblOne);
th = new Thread(this);
th.start(); // here thread starts
}
public void run()
{
try
{
do
{
dd = new Date();
lblOne.setText(dd.getHours() + " : " + dd.getMinutes() + " : " + dd.getSeconds());
Thread.sleep(1000); // 1000 = 1 second
}while(th.isAlive());
}
catch(Exception e)
{
}
}
public static void main(String[] args)
{
new TimeInSeconds();
}
}
You can run this program and get the output.
For more info on date and time in java you can refer links below,
https://docs.oracle.com/javase/tutorial/datetime/iso/datetime.html
https://docs.oracle.com/javase/7/docs/api/java/sql/Date.html
http://www.flowerbrackets.com/date-time-java-program/
Add a loop with an increment statement, so the clock will keep ticking until given condition.
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.
Use simple date formatter with hh:mm as format.
SimpleDateFormat sdf = new SimpleDateFormat("HH:MM a");
Click here for complete program.
public void ShowTime() {
new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Date d = new Date();
SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyy hh:mm:ss a");
time.setText(s.format(d)); //time= jlabel
}
}).start();
}
Continuously Change time(refresh every second)