Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I say 5 seconds from now in Java?

Tags:

java

date

I am looking at the Date documentation and trying to figure out how I can express NOW + 5 seconds. Here's some pseudocode:

import java.util.Date public class Main {      public static void main(String args[]) {          Date now = new Date();          now.setSeconds(now.getSeconds() + 5);     } } 
like image 583
Nick Stinemates Avatar asked Oct 31 '09 19:10

Nick Stinemates


People also ask

How do you subtract seconds in Java?

Easiest solution: if it is the current date use: Long seconds= 10; //update in seconds //seconds*1000 to convert second to millisecond Date dateAfterUpdation = new Date(System. currentTimeMillis() - (seconds*1000) );

How do I count seconds in Java?

To compute the elapsed time of an operation in seconds in Java, we use the System. currentTimeMillis() method.

What is Java time Millis?

currentTimeMillis() method returns the current time in milliseconds. The unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.


1 Answers

Date is almost entirely deprecated and is still there for backward compatibility reasons. If you need to set particular dates or do date arithmetic, use a Calendar:

Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale. calendar.add(Calendar.SECOND, 5); System.out.println(calendar.getTime()); 
like image 177
Pascal Thivent Avatar answered Oct 04 '22 12:10

Pascal Thivent