用 Java 怎么说从现在开始的5秒钟?

我正在看日期 文件和试图找出我如何可以表达现在 + 5秒。下面是一些伪代码:

import java.util.Date
public class Main {


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

你可使用:

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

Date.getTime()setTime()始终指自1970年1月1日协调世界时上午12点以来的毫秒。

Joda 时间

但是,如果您所做的不仅仅是最简单的日期/时间处理,我强烈建议您使用 乔达时间。它是一个比 Java 内置支持更强大、更友好的 很多库。

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

爪哇时间

Joda-Time 后来启发了内置在 Java8中的新 Java.time 软件包

我刚从 Java 文件发现了这个

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

有什么我需要注意的惯例吗?

Date 几乎完全被废弃了,因为向下兼容的原因仍然存在。如果需要设置特定的日期或进行日期算术,请使用 日历:

Calendar calendar = Calendar.getInstance(); // gets a calendar using the default time zone and locale.
calendar.add(Calendar.SECOND, 5);
System.out.println(calendar.getTime());

来自一句俏皮话:

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

根据我对你的例子的理解,‘ now’实际上是‘ now’,而“ System.currentTimeMillis ()’恰好代表了同样的‘ now’概念: -)

但是,没错,对于比 Joda time API 更复杂的东西来说。

正如其他人指出的那样,在 Joda中要容易得多:

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

我强烈建议您迁移到 Joda。几乎所有与 Java 日期相关的问题都可以归结为 Joda 的建议: —— Joda API 应该是新的标准 Java 日期 API (JSR310)的基础,因此您将迁移到一个新的标准。

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

忽略 Dates,专注于问题。

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

在爪哇,

long now = System.currentTimeMillis();

使用 TimeUtilnow开始5秒是:

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

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

更新: 使用 爪哇时间类查看 我的新答案。我将这个答案作为历史完整保留。


帕斯卡 · 蒂文特的答案和乔恩 · 斯基特的 答案都是正确和好的。这里有一些额外的信息。

5秒 = PT5S(ISO8601)

另一种表达“5秒钟后”想法的方法是使用 ISO 8601定义的标准格式在字符串中。期间/期间格式有这样的模式 PnYnMnDTnHnMnS,其中 P标记的开始和 T分离的日期部分从时间部分。

5秒是 PT5S

Joda 时间

Joda 时间2.8库可以生成和解析这样的持续时间/周期字符串。参见 PeriodDurationInterval类。可以在 DateTime对象中添加或减去句点对象。

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

试试这个。

    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

博士

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.

爪哇时间

使用现代的 爪哇时间类,多年前取代了可怕的 DateCalendar类。

协调世界时

若要在 UTC 中工作,请使用 Instant

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

时区

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

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

Duration

您可以对要添加的时间量和粒度进行软编码。

Duration d = Duration.ofSeconds( 5 ) ;
Instant later = Instant.now().plus( d ) ;  // Soft-code the amount of time to add or subtract.

关于 爪哇时间

< em > java.time 框架内置于 Java8及更高版本中。这些类取代了令人讨厌的旧的 遗产日期时间类,如 java.util.DateCalendarSimpleDateFormat

要了解更多,请参阅 < em > Oracle 教程 。并搜索堆栈溢出许多例子和解释。规范是 JSR 310

现在在 维修模式中的 尤达时间项目建议迁移到 爪哇时间类。

您可以直接与数据库交换 爪哇时间对象。使用与 JDBC 4.2或更高版本兼容的 JDBC 驱动程序。不需要字符串,不需要 java.sql.*类。Hibernate 5 & JPA 2.2支持 爪哇时间

从哪里获得 java.time 类?