简体   繁体   English

Java内置日期操作和比较

[英]Java Built In Date Manipulation and Comparison

I'm looking to create a datetime stamp, then add 10 hours to it, then have a thread check to see if the time has elapsed. 我想创建一个日期时间戳,然后向其添加10个小时,然后进行线程检查以查看时间是否已经过去。

I read through, Time comparison but it seems a bit complicated/convoluted for something so simple. 我读了一下, 时间比较,但是对于这么简单的事情似乎有点复杂/复杂。 Especially if your time comparison goes across midnight. 特别是如果您的时间比较是午夜。

My understanding is that java's underlying datetime, is suppose to be a long, if this is true, is there a simple way to add another long to it, such as the number equivalent of 10 hours? 我的理解是,java的基础日期时间假设是一个很长的时间(如果是这样),是否有一种简单的方法为其添加另一个长的时间,例如等于10小时的数字? Or some other means such as adding two dates? 还是其他一些方法,例如添加两个日期?

Note: The solution needs to be part of core java, can't be part of a 3rd party lib. 注意:该解决方案必须是核心Java的一部分,不能成为第三方库的一部分。

You can use a Calendar to perform that math, 您可以使用日历来执行该数学运算,

Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR, 10); // Add 10 hours.
Date date2 = cal.getTime(); // Now plus 10 hours.
Date date = new Date(); // Now.

You can use the Date.getTime() method to obtain the underlying timestamp, the timestamp is basically the number of milliseconds elapsed since a defined base instant (1970-01-01 00:00:00 IIRC). 您可以使用Date.getTime()方法获取基础时间戳,该时间戳基本上是自定义的基本时刻(1970-01-01 00:00:00 IIRC)起经过的毫秒数。

System.currentTimeMillis() allows you the get the "now" instant directly, without any detours using Date , Calendar and the like. System.currentTimeMillis()允许您直接获取“现在”即时信息,而无需使用DateCalendar等进行绕行。

The timestamp can then be manipulated basic math: 然后可以对时间戳进行基本数学运算:

 timestamp += TimeUnit.MILLISECONDS.convert(10, TimeUnit.HOURS);

Example of adding 10 hours: 加10小时的示例:

long nowInMilliSince1970 = System.currentTimeMillis();
long tenHoursAsMilli = TimeUnit.MILLISECONDS.convert(10L, TimeUnit.MINUTES);
long tenHoursLater = nowInMilliSince1970 + tenHoursAsMilli;
System.out.println("now in milliseconds: \t\t" + nowInMilliSince1970);
System.out.println("10 hours in milliseconds: \t" + tenHoursAsMilli);
System.out.println("10 hours from now: \t\t" + tenHoursLater);

Checking if the timestamp is in the past is as easy as: 检查时间戳是否过去很容易:

 if (timestamp < System.currentTimeMillis()) {
     System.out.println("timestamp is in the past");
 }

Do note that direct timestamp math has no concept of daylight saving and time zones. 请注意,直接时间戳数学没有夏令时和时区的概念。 If you want that, use a Calendar for math - Calendar implements the dirty exceptional rules for that. 如果需要,请使用日历进行数学运算- Calendar为此实现了肮脏的例外规则。

Another way of achieving it using just JDK built in stuff is: 仅使用内置的JDK来实现此目标的另一种方法是:

long tenHoursFromNow = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(10);

and then in your Thread you would check: 然后在您的线程中检查:

if(System.currentTimeMillis() > tenHoursFromNow)
{
        //Do something as the time has elapsed 
}

Although I would argue that the use of Calendar and Date is clearer as to what the intention of your code is trying to achieve. 尽管我认为使用Calendar和Date可以更清楚地了解代码的意图。

The bundled java.util.Date and .Calendar are notoriously troublesome. 捆绑的java.util.Date和.Calendar非常麻烦。 They really should be avoided. 确实应该避免它们。

You stated a requirement of no added libraries. 您声明了不添加任何库的要求。 So see the java.time part of my answer, using the new package newly added to Java 8. But I urge you to reconsider your reluctance to add a library, especially if you cannot move to Java 8 yet; 因此,请使用新添加到Java 8中的新程序包来查看答案的java.time部分。但是,我敦促您重新考虑不愿添加库的情况,特别是如果您现在还不能迁移到Java 8时,尤其如此。 juDate/Calendar really are that bad. juDate / Calendar真的很糟糕。

Both libraries handle anomalies such as Daylight Saving Time. 这两个库都处理诸如夏令时之类的异常。

Consider specifying a time zone rather than rely on the JVM's default. 考虑指定时区,而不要依赖JVM的默认时区。 Generally best to work in UTC , and then translate to a local time zone for presentation to the user. 通常最好在UTC中工作,然后转换为本地时区以呈现给用户。

java.time java.time

The java.time package is newly added to Java 8 . java.time软件包是新添加到Java 8中的 Inspired by Joda-Time but re-architected. Joda-Time启发,但重新设计。 Defined by JSR 310 . JSR 310定义。 Extended by the threeten-extra project. threeten-extra项目扩展。

ZonedDateTime tenHoursLater = ZonedDateTime.now().plusHours( 10 );

Joda-Time 乔达时代

Using the Joda-Time 2.3 library. 使用Joda-Time 2.3库。

DateTime tenHoursLater = DateTime.now().plusHours( 10 );

For more info on this kind of use of Joda-Time, see my answer to a similar question. 有关使用Joda-Time的更多信息,请参阅对类似问题的回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM