从现在开始,我如何说Java?

时间:2009-10-31 19:30:35

标签: java date

我正在查看日期documentation,并试图弄清楚我如何表达现在+ 5秒。这是一些伪代码:

import java.util.Date
public class Main {

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

11 个答案:

答案 0 :(得分:76)

Date几乎完全被弃用,并且由于向后兼容的原因仍然存在。如果您需要设置特定日期或进行日期算术,请使用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());

答案 1 :(得分:50)

您可以使用:

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

Date.getTime()setTime()总是指自1970年1月1日上午12点UTC以来的毫秒数。

约达时间

但是,如果你做的不仅仅是最简单的日期/时间处理,我强烈建议你使用Joda Time。与Java中的内置支持相比,它是一个很多更强大,更友好的库。

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

java.time

Joda-Time后来启发了Java 8中内置的新java.time package

答案 2 :(得分:22)

来自单行 - hacky dep。:

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

正如我从你的例子中所理解的那样,'now'实际上是'现在',而“System.currentTimeMillis()”碰巧代表了同样的“现在”概念: - )

但是,是的,因为比Joda时间API更复杂的一切。

答案 3 :(得分:6)

正如其他人所指出的那样,Joda更容易:

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

我强烈建议您迁移到Joda。几乎所有关于SO的Java日期相关问题都解决了Joda建议:-) Joda API应该是新标准Java date API(JSR310)的基础,因此您将迁移到新标准。

答案 4 :(得分:5)

忽略Dates并专注于此问题。

我的偏好是使用java.util.concurrent.TimeUnit,因为它增加了我的代码的清晰度。

在Java中,

long now = System.currentTimeMillis();

使用now TimeUtil后5秒:

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

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

答案 5 :(得分:3)

Pascal Thivent的

The Answer和Jon Skeet的the Answer都是正确和良好的。这里有一些额外的信息。

五秒= PT5S(ISO 8601)

另一种表达"五秒钟后的想法"是使用ISO 8601定义的标准格式的字符串。 duration/period format具有此模式PnYnMnDTnHnMnS,其中P标记开头,T将日期部分与时间部分分开。

所以五秒是PT5S

约达时间

Joda-Time 2.8库可以生成和解析这样的持续时间/句点字符串。请参阅PeriodDurationInterval课程。您可以在DateTime个对象中添加和减去Period对象。

搜索StackOverflow以获取许多示例和讨论。这是一个简单的例子。

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

转储到控制台。

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

跑步时。

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

答案 6 :(得分:2)

我刚从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));
  }
}

我应该注意一个约定吗?

答案 7 :(得分:1)

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

答案 8 :(得分:1)

tl; dr

public class Product
    {
        public string ProductName { get; set; }
        public List<Option> Options { get; set; }        
    }


public class Options
    {
        public int Quantity { get; set; } 
    }

java.time

使用多年前的现代 java.time 类取代了可怕的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. Date类。

UTC

要使用UTC,请使用Instant

Calendar

时区

要在特定时区工作,请使用ZonedDateTime

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

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

您可以对要添加的时间和数量进行软编码。使用Duration类。

Duration

答案 9 :(得分:0)

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

答案 10 :(得分:0)

尝试一下。

    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