问题
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");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Now it shows me: 2012/12/11 00:36:53 when I run it.
But I want it to count the time during running it.
So by example now when I run it on 00:37:53 it shows this time, but I want 00:37:53 at starting and I stop running it on 00:40:55 . I want that it shows me 00:37:53, 00:37:54, 00:37:55 and so on.
Now how can I do this?
回答1:
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.
Edit
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();
}
回答2:
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.
回答3:
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/
回答4:
Use simple date formatter with hh:mm as format.
SimpleDateFormat sdf = new SimpleDateFormat("HH:MM a");
Click here for complete program.
回答5:
Add a loop with an increment statement, so the clock will keep ticking until given condition.
回答6:
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)
来源:https://stackoverflow.com/questions/13811224/java-display-current-time