How do I say 5 seconds from now in Java?

后端 未结 11 1793
青春惊慌失措
青春惊慌失措 2020-12-02 15:29

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 clas         


        
11条回答
  •  渐次进展
    2020-12-02 15:39

    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?

    • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
      • Java 9 brought some minor features and fixes.
    • Java SE 6 and Java SE 7
      • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
    • Android
      • Later versions of Android (26+) bundle implementations of the java.time classes.
      • For earlier Android (<26), a process known as API desugaring brings a subset of the java.time functionality not originally built into Android.
        • If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….

提交回复
热议问题