检查是否已经过了24小时(从字符串中读取)

我将日期保存在文件中,格式如下。

Sat Jul 21 23:31:55 EDT 2012 

如何检查24小时是否过去了? 我是初学者所以请解释一下=)

我不确定我是否完全理解这个问题 – 您是否有两个比较日期,或者您是否希望在24小时后定期检查? 如果比较两个日期/时间,我建议看看joda或者date4j。 使用joda,可以考虑使用两个日期之间的间隔:

 Interval interval = new Interval(previousTime, new Instant()); 

以前的时间是你提到的时间

你可以这样做:

 try { // reading text... Scanner scan = new Scanner( new FileInputStream( new File( "path to your file here..." ) ) ); String dateString = scan.nextLine(); // creating a formatter. // to understand the format, take a look here: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html // EEE: Day name of week with 3 chars // MMM: Month name of the year with 3 chars // dd: day of month with 2 chars // HH: hour of the day (0 to 23) with 2 chars // mm: minute of the hour with 2 chars // ss: second of the minute with 2 chars // zzz: Timezone with 3 chars // yyyy: year with 4 chars DateFormat df = new SimpleDateFormat( "EEE MMM dd HH:mm:ss zzz yyyy", Locale.US ); // parsing the date (using the format above, that matches with your date string) Date date = df.parse( dateString ); // now! Date now = new Date(); // gets the differente between the parsed date and the now date in milliseconds long diffInMilliseconds = now.getTime() - date.getTime(); if ( diffInMilliseconds < 0 ) { System.out.println( "the date that was read is in the future!" ); } else { // calculating the difference in hours // one hour have: 60 minutes or 3600 seconds or 3600000 milliseconds double diffInHours = diffInMilliseconds / 3600000D; System.out.printf( "%.2f hours have passed!", diffInHours ); } } catch ( FileNotFoundException | ParseException exc ) { exc.printStackTrace(); } 

我建议将您的信息存储为具有compareTo ()函数的java.util.Calendar

如果要立即与当前时间进行比较,可以使用System.getCurrentTimeMillis()来获取当前时间。

定义一天

你真的是指一天或24小时吗? 由于夏令时无意义,一天的长度可能会有所不同,例如美国的23或25小时。

避免使用3个字母的时区代码

String格式是日期时间的可怕表示。 很难解析。 它使用3个字母的时区代码,这些代码既不标准也不唯一。 如果可能,请选择其他格式。 显而易见的选择是ISO 8601 ,例如: 2014-07-08T04:17:01Z

使用适当的时区名称 。

避免使用juDate和.Calendar

与Java捆绑在一起的java.util.Date和.Calendar类非常麻烦。 避免他们。

而是使用古老的Joda-Time库或Java 8中捆绑的新java.time包(并受到Joda-Time的启发)。

乔达时间

以下是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小时(或第二天)。

 DateTime twentyFourHoursLater = target.plusHours( 24 ); 

测试当前时刻是否发生。

 boolean expired = now.isAfter( twentyFourHoursLater ); 

或者,如果您想要第二天而不是24小时,请使用plusDays而不是plusHours 。 如有必要,请调整到所需的时区。 时区是至关重要的,因为它定义了日期/日期并应用了夏令时等exception情况的规则。

 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.