【问题标题】:How to convert String (hh:mm) to date with current date [duplicate]如何将字符串(hh:mm)转换为当前日期的日期[重复]
【发布时间】:2017-11-09 22:03:10
【问题描述】:

我想从字符串计算当前时间和时间之间的差异(以分钟为单位)。

我有这样的字符串(来自 SQlite 数据库):

 String time1= "22:50";

我得到的当前日期为:

  Date currentDate = new Date()
   long test = currentData.getTime();

解析字符串至今:

 SimpleDateFormat dateFormat = new SimpleDateFormat(
                                "yyyy-MM-dd HH:mm:ss");
oldDate = dateFormat.parse(time1);

然后区别:

  diff = test - oldDate.getTime();
  long seconds = diff / 1000;
  long minutes = seconds / 60;

但主要问题是由于缺少当前数据信息(我只有时间)。 我想要:当前数据 + 字符串中的时间,然后将其与当前日期和时间进行比较。

【问题讨论】:

  • 基本上,您需要从数据库中以"yyyy-MM-dd "+time1+":ss" 的格式构造一个带有时间的字符串,然后将其解析为SimpleDateFormat。然后您可以将其与当前日期/时间进行比较。

标签: java android date time


【解决方案1】:

使用 Java 8 时间,将时间解析为 LocalTime,将其应用于具有今天日期的 LocalDate,然后根据需要格式化结果。

简而言之:

// returns "2017-11-09 22:50:00"
LocalDate.now().atTime(LocalTime.parse("22:50"))
         .format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))

如果您的 Android 还没有 Java 8,请使用 ThreeTen Android Backport

【讨论】:

  • 我试过了,但是在 gradle insert 和 AndroidThreeTen.init(this);在 OnCreate 中,仍然得到:调用需要 API 级别 26。
  • 使用LocalTime.now(desiredZoneId)然后ChronoUnit.MINUTES.between(timeFromDb, timeNow)不是更简单吗?当然,这取决于具体要求。
猜你喜欢
  • 2014-03-23
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
  • 2016-02-28
  • 2011-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多