开发者

How do I say 5 seconds from now in Java?

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
publ开发者_StackOverflow中文版ic class Main {

    public static void main(String args[]) {
         Date now = new Date();
         now.setSeconds(now.getSeconds() + 5);
    }
}


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


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.


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.


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….


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.


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


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


I just found this from java docs

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?


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜