【问题标题】:Calculate end time and start time difference in mins and verify entered time in android以分钟为单位计算结束时间和开始时间差并验证在android中输入的时间
【发布时间】:2016-06-20 12:18:10
【问题描述】:

我必须计算两次(结束时间 - 开始时间)之间的时间差。时间是 hh:mm 格式,我想要整数 MINUTS 的差异? 还有一件事如何验证用户输入的时间在 1 到 24 小时之间?

【问题讨论】:

  • 最好的原因是在 long 中找到差异,或者您可以使用 Joda 库。

标签: java android


【解决方案1】:

使用此 API 将其解析为 hava LocalTime

LocalTime.parse(userInput, hhmmFormatter)

(请参阅此处的 API 文档https://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#parse-java.lang.CharSequence-java.time.format.DateTimeFormatter-

对两个输入执行此操作。根据文档,如果格式与 hh:mm(由您的 hhmmFormatter 实例定义)不匹配,此方法将抛出 DateTimeParseException,因此您可以捕获它并按照您的意愿处理它。

您可以使用 DateTimeFormatter.ofPattern 创建自己的 hhmmFormatter,但我建议您直接使用标准

 DateTimeFormatter.ISO_LOCAL_TIME

非常适合您的情况。更多细节在这里https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html#ISO_LOCAL_TIME

所以你可以简单地做

try {
  // NOTE: you can move these into their own try/catch so you can handle bad user input separately if you wish
  final LocalTime time1 = LocalTime.parse(userInput1, DateTimeForamatter.ISO_LOCAL_TIME);
  final LocalTime time2 = LocalTime.parse(userInput2, DateTimeForamatter.ISO_LOCAL_TIME);
  final long differenceInNanos = (time2.toNanoOfDay() - time1.toNanoOfDay());
  final long differenceInSeconds = TimeUnit.NANOSECONDS.toSeconds(differenceInNanos)
}
catch(DateTimeParseException e){
   // TODO code to handle bad user input
}

(TimeUnit https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html 的文档)

请注意,如果您想处理用户可能指定跨天时间的情况,您没有在问题中注明,所以我只向您展示 LocalTime。您可以轻松地将其转换为最一般的 ZonedDateTime 案例并执行非常相似的操作。

【讨论】:

  • 谢谢。我使用的是当地时间。我不需要用户指定跨天的时间。它解决了我的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-11
  • 1970-01-01
  • 2020-01-02
  • 2022-12-16
  • 1970-01-01
  • 2021-11-14
相关资源
最近更新 更多