Date Stopwatch



Date Stopwatch
How do you get the time in Java?

I want to know, if it’s possible, how to check the time in Java. Say, I wanted to write a program that mimics a stopwatch or something like that. How do I count how many seconds pass?

There are [at least] two ways to get time in Java, depending on accuracy requirements:

1) use System.currentTimeMillis() – this gets the current time in milliseconds (1/1000 of a second). This is probably sufficient for a stopwatch application. currentTimeMillis technically returns the number of milliseconds past January 1, 1970 UTC so you can use this to obtain date/month/year/etc.

2) use System.nanoTime() – this will retrieve the current system time in nano seconds (1/1,000,000,000 of a second). nanoTime’s return value is relative to the system start time, not a standard date like currentTimeMillis. Nanosecond precision is probably overkill for a basic stopwatch application.

Both methods above return time as a long. Essentially, your stopwatch would run like this:

// start!
long startTime = System.currentTimeMillis();

// update clock, assumes that when the user presses the “stop” button, the boolean variable “running” would be set to false
while(running) {
long currentRunningTimeInMilliSeconds = System.currentTimeMillis() – startTime;
// this method would update the clock, perhaps by converting to seconds (dividing by 1000)
updateClock(currentRunningTimeInMilliSeconds);
}

Unique Stainless Steel Six Pointer Wrist Watch with Date Stopwatch-Black dial/Leather Band

Subscribe to our Newsletter