用 Java 怎么说 5 秒后?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1655357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I say 5 seconds from now in Java?
提问by Nick Stinemates
I am looking at the Date documentationand trying to figure out how I can express NOW + 5 seconds. Here's some pseudocode:
我正在查看日期文档并试图弄清楚如何表达 NOW + 5 秒。这是一些伪代码:
import java.util.Date
public class Main {
public static void main(String args[]) {
Date now = new Date();
now.setSeconds(now.getSeconds() + 5);
}
}
采纳答案by Pascal Thivent
Dateis 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:
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());
回答by Jon Skeet
You can use:
您可以使用:
now.setTime(now.getTime() + 5000);
Date.getTime()and setTime()always refer to milliseconds since January 1st 1970 12am UTC.
Date.getTime()并setTime()始终指自 UTC 时间 1970 年 1 月 1 日凌晨 12 点以来的毫秒数。
Joda-Time
乔达时间
However, I would strongly advise you to use Joda Timeif you're doing anything more than the very simplest of date/time handling. It's a muchmore capable and friendly library than the built-in support in Java.
但是,如果您要做的不仅仅是最简单的日期/时间处理,我强烈建议您使用Joda Time。这是一个很多更强大和友好的库比内置的Java支持。
DateTime later = DateTime.now().plusSeconds( 5 );
java.time
时间
Joda-Time later inspired the new java.time packagebuilt into Java 8.
Joda-Time 后来启发了Java 8 中内置的新java.time 包。
回答by Nick Stinemates
I just found this from java docs
我刚刚从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));
}
}
Is there a convention I should be aware of?
是否有我应该注意的约定?
回答by AlexPat
From the one-liner-hacky dep.:
来自 one-liner-hacky 部门:
new Date( System.currentTimeMillis() + 5000L)
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 :-)
正如我从你的例子中理解的那样,“现在”实际上是“现在”,而“System.currentTimeMillis()”恰好代表了同样的“现在”概念:-)
But, yup, for everything more complicated than that the Joda time API rocks.
但是,是的,对于比 Joda 时间 API 摇滚更复杂的一切。
回答by Brian Agnew
As others have pointed out, in Jodait's much easier:
正如其他人指出的那样,在Joda 中要容易得多:
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.
我强烈建议您迁移到 Joda。几乎所有关于 SO 的 Java 日期相关问题都解决了 Joda 建议 :-) Joda API 应该是新标准 Java 日期 API (JSR310) 的基础,因此您将迁移到新标准。
回答by overflow
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);
}
}
回答by Alexandre Santos
Ignoring Datesand focusing on the question.
忽略Dates并专注于问题。
My preference is to use java.util.concurrent.TimeUnitsince it adds clarity to my code.
我的偏好是使用,java.util.concurrent.TimeUnit因为它增加了我的代码的清晰度。
In Java,
在爪哇,
long now = System.currentTimeMillis();
5 seconds from nowusing TimeUtilis:
从5秒now使用TimeUtil为:
long nowPlus5Seconds = now + TimeUnit.SECONDS.toMillis(5);
Reference: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html
参考:http: //docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html
回答by Basil Bourque
UPDATE:See my new Answerusing java.timeclasses. I am leaving this Answer intact as history.
更新:使用java.time类查看我的新答案。我将这个答案完好无损地作为历史。
The Answerby Pascal Thivent and the Answerby Jon Skeet are both correct and good. Here's a bit of extra info.
答案由Pascal Thivent和应答通过乔恩斯基特都是正确的,良好的。这里有一些额外的信息。
Five Seconds = PT5S(ISO 8601)
五秒 = 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 formathas this pattern PnYnMnDTnHnMnSwhere the Pmarks the beginning and the Tseparates the date portion from time portion.
另一种表达“五秒后”概念的方法是使用ISO 8601定义的标准格式在字符串中。的持续时间/周期格式具有这种模式PnYnMnDTnHnMnS,其中P标记的开始和T分离时间部分的时间部分。
So five seconds is PT5S.
所以五秒是PT5S。
Joda-Time
乔达时间
The Joda-Time2.8 library can both generate and parse such duration/period strings. See the Period, Duration, and Intervalclasses. You can add and subtract Period objects to/from DateTimeobjects.
该乔达时间2.8库既可以生成和解析这样的持续时间/周期字符串。见Period,Duration和Interval类。您可以将 Period 对象添加到/从DateTime对象中减去。
Search StackOverflow for many examples and discussions. Here's one quick example.
在 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 );
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
回答by Kalai Prakash
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());
回答by Mr. Mak
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

