检查是否已经过了24小时(从字符串中读取) [英] Check if 24 hours have passed (reading from a string)
问题描述
我将日期保存在文件中,格式如下。
I am saving date's in a file in the following format as a string.
Sat Jul 21 23:31:55 EDT 2012
如何检查24小时是否过去了?我是初学者所以请稍微解释一下=)
How can I check if 24 hours have passed? I am a beginner so please explain it a little bit =)
推荐答案
定义一天
你真的是指一天或24小时吗?由于夏令时无意义,一天的长度可能会有所不同,例如美国的23或25小时。
Define A Day
Do you really mean one day or 24-hours? Because of Daylight Saving Time nonsense, a day can vary in length such as 23 or 25 hours in the United States.
字符串格式是日期时间的可怕表示。很难解析。它使用3个字母的时区代码,这些代码既不标准也不唯一。如果可能,请选择其他格式。显而易见的选择是 ISO 8601 ,例如: 2014-07-08T04 :17:01Z
。
That String format is a terrible representation of a date-time. It is difficult to parse. It uses a 3-letter time zone code, and such codes are neither standardized nor unique. If possible, choose another format. The obvious choice is ISO 8601, for example: 2014-07-08T04:17:01Z
.
使用正确的时区名称。
与Java捆绑在一起的java.util.Date和.Calendar类非常麻烦。避免他们。
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
而是使用古老的 Joda-Time 库或Java 8中捆绑的新java.time包(灵感来自Joda-Time)。
Instead use either the venerable Joda-Time library or the new java.time package bundled in Java 8 (and inspired on Joda-Time).
以下是Joda-Time中的一些示例代码。
Here is some example code in Joda-Time.
获取当前时刻。
DateTime now = DateTime.now();
解析输入字符串。
String input = "Sat Jul 21 23:31:55 EDT 2012";
DateTime formatter = DateTimeFormat.forPattern( "EEE MMM dd HH:mm:ss zzz yyyy" ).with Locale( java.util.Locale.ENGLISH );
DateTime target = formatter.parseDateTime( input );
计算24小时(或第二天)。
Calculate 24 hours (or next day).
DateTime twentyFourHoursLater = target.plusHours( 24 );
测试当前时刻是否发生。
Test if current moment happened after.
boolean expired = now.isAfter( twentyFourHoursLater );
或者,如果您想要第二天而不是24小时,请使用 plusDays
而不是 plusHours
。如有必要,请调整到所需的时区。时区至关重要因为它定义了日期/日期并应用了异常情况的规则,例如夏令时。
Or, if you want next day rather than 24-hours, use plusDays
rather than plusHours
. If necessary, adjust to desired time zone. Time zone is crucial as it defines the day/date and applies rules for anomalies such as Daylight Saving Time.
DateTime targetAdjusted = target.withZone( DateTimeZone.forID( "Europe/Paris" ) );
…
DateTime aDayLater = targetAdjusted.plusDays( 1 ); // Go to next day, accounting for DST etc.
boolean expired = now.isAfter( aDayLater ); // Test if current moment happened after.
这篇关于检查是否已经过了24小时(从字符串中读取)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!