How do I say 5 seconds from now in Java?

JavaDate

Java Problem Overview


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);
    }
}

Java Solutions


Solution 1 - Java

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());

Solution 2 - Java

You can use:

now.setTime(now.getTime() + 5000);

Date.getTime() and setTime() always refer to milliseconds since January 1st 1970 12am UTC.

Joda-Time

However, I would strongly advise you to use Joda Time if you're doing anything more than the very simplest of date/time handling. It's a much more capable and friendly library than the built-in support in Java.

DateTime later = DateTime.now().plusSeconds( 5 );

java.time

Joda-Time later inspired the new java.time package built into Java 8.

Solution 3 - Java

From the one-liner-hacky dep.:

new Date( System.currentTimeMillis() + 5000L)

As I understand it from your example, 'now' is really 'now', and "System.currentTimeMillis()' happens to represent that same 'now' concept :-)

But, yup, for everything more complicated than that the Joda time API rocks.

Solution 4 - Java

tl;dr

Instant             // Use modern `java.time.Instant` class to represent a moment in UTC.
.now()              // Capture the current moment in UTC.
.plusSeconds( 5 )   // Add five seconds into the future. Returns another `Instant` object per the Immutable Objects pattern.

java.time

Use the modern java.time classes that years ago supplanted the terrible Date & Calendar classes.

UTC

To work in UTC, use Instant.

Instant later = Instant.now().plusSeconds( 5 ) ;

Time zone

To work in a specific time zone, use ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime later = ZonedDateTime.now( z ).pluSeconds( 5 ) ;

Duration

You can soft-code the amount and granularity of time to add. Use the Duration class.

Duration d = Duration.ofSeconds( 5 ) ;
Instant later = Instant.now().plus( d ) ;  // Soft-code the amount of time to add or subtract.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Solution 5 - Java

As others have pointed out, in Joda it's much easier:

DateTime dt = new DateTime();
DateTime added = dt.plusSeconds(5);

I would strongly recommend you migrate to Joda. Almost any Java date-related question on SO resolves to a Joda recommendation :-) The Joda API is supposed to be the basis of the new standard Java date API (JSR310), so you'll be migrating towards a new standard.

Solution 6 - Java

Ignoring Dates and focusing on the question.

My preference is to use java.util.concurrent.TimeUnit since it adds clarity to my code.

In Java,

long now = System.currentTimeMillis();

5 seconds from now using TimeUtil is:

long nowPlus5Seconds = now + TimeUnit.SECONDS.toMillis(5);

Reference: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html

Solution 7 - Java

UPDATE: See my new Answer using java.time classes. I am leaving this Answer intact as history.


The Answer by Pascal Thivent and the Answer by Jon Skeet are both correct and good. Here's a bit of extra info.

Five Seconds = PT5S (ISO 8601)

Another way to express the idea of "five seconds later" is in a string using the standard formats defined by ISO 8601. The duration/period format has this pattern PnYnMnDTnHnMnS where the P marks the beginning and the T separates the date portion from time portion.

So five seconds is PT5S.

Joda-Time

The Joda-Time 2.8 library can both generate and parse such duration/period strings. See the Period, Duration, and Interval classes. You can add and subtract Period objects to/from DateTime objects.

Search StackOverflow for many examples and discussions. Here's one quick example.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
DateTime then = now.plusSeconds( 5 );
Interval interval = new Interval( now, then );
Period period = interval.toPeriod( );

DateTime thenAgain = now.plus( period );

Dump to console.

System.out.println( "zone: " + zone );
System.out.println( "From now: " + now + " to then: " + then );
System.out.println( "interval: " + interval );
System.out.println( "period: " + period );
System.out.println( "thenAgain: " + thenAgain );

When run.

zone: America/Montreal
From now: 2015-06-15T19:38:21.242-04:00 to then: 2015-06-15T19:38:26.242-04:00
interval: 2015-06-15T19:38:21.242-04:00/2015-06-15T19:38:26.242-04:00
period: PT5S
thenAgain: 2015-06-15T19:38:26.242-04:00

Solution 8 - Java

I just found this from [java docs][1]

import java.util.Calendar;

public class Main {

  public static void main(String[] args) {
    Calendar now = Calendar.getInstance();
    System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));

    now.add(Calendar.SECOND, 100);
    System.out.println("New time after adding 100 seconds : " + now.get(Calendar.HOUR_OF_DAY) + ":"
        + now.get(Calendar.MINUTE) + ":" + now.get(Calendar.SECOND));
  }
}

Is there a convention I should be aware of? [1]: http://www.java2s.com/Code/Java/Development-Class/AddsecondstocurrentdateusingCalendaraddmethod.htm

Solution 9 - Java

        String serverTimeSync = serverTimeFile.toString();
        SimpleDateFormat serverTime = new SimpleDateFormat("yyyy,MM,dd,HH,mm,ss");
        Calendar c = Calendar.getInstance();
        c.setTime(serverTime.parse(serverTimeSync));
        c.add(Calendar.MILLISECOND, 15000);
        serverTimeSync = serverTime.format(c.getTime());

Solution 10 - Java

public class datetime {

    public String CurrentDate() {        
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
        String currentTime = sdf.format(dt);
        return currentTime;
    }

    public static void main(String[] args) {
        class SayHello extends TimerTask {
            datetime thisObj = new datetime();
            public void run() {
                String todaysdate = thisObj.CurrentDate();
                System.out.println(todaysdate);
            }
        }
        Timer timer = new Timer();
        timer.schedule(new SayHello(), 0, 5000); 
    }
}

Solution 11 - Java

Try This..

    Date now = new Date();
    System.out.println(now);

    Calendar c = Calendar.getInstance();
    c.setTime(now);
    c.add(Calendar.SECOND, 5);
    now = c.getTime();

    System.out.println(now);
	
	// Output
	Tue Jun 11 16:46:43 BDT 2019
	Tue Jun 11 16:46:48 BDT 2019

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick StinematesView Question on Stackoverflow
Solution 1 - JavaPascal ThiventView Answer on Stackoverflow
Solution 2 - JavaJon SkeetView Answer on Stackoverflow
Solution 3 - JavaAlexPatView Answer on Stackoverflow
Solution 4 - JavaBasil BourqueView Answer on Stackoverflow
Solution 5 - JavaBrian AgnewView Answer on Stackoverflow
Solution 6 - JavaAlexandre SantosView Answer on Stackoverflow
Solution 7 - JavaBasil BourqueView Answer on Stackoverflow
Solution 8 - JavaNick StinematesView Answer on Stackoverflow
Solution 9 - JavaKalai PrakashView Answer on Stackoverflow
Solution 10 - JavaoverflowView Answer on Stackoverflow
Solution 11 - JavaMr. MakView Answer on Stackoverflow