How do I say 5 seconds from now in Java?

后端 未结 11 1658
青春惊慌失措
青春惊慌失措 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….
    0 讨论(0)
  • 2020-12-02 15:40

    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.

    0 讨论(0)
  • 2020-12-02 15:41

    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.

    0 讨论(0)
  • 2020-12-02 15:44

    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

    0 讨论(0)
  • 2020-12-02 15:48
    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); 
        }
    }
    
    0 讨论(0)
  • 2020-12-02 15:51
            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());
    
    0 讨论(0)
提交回复
热议问题