How do I say 5 seconds from now in Java?

Viewed 118274

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

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?

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
Related