您的输入表示本地日期/时间 (2018-04-02 20:06:42),要获取经过的时间,您需要定义要使用的时区。
输入对应于 2018 年 4 月 2 日晚上 8:06:42,但在哪里?请注意,在世界不同地区,晚上 8 点发生在不同的时刻,具体取决于您所在的时区。在不知道输入所指的确切时区的情况下,无法将其与“现在”进行比较。
如果您有办法找出与输入相对应的时区,那么您可以开始执行以下操作:
String input = "2018-04-02 20:06:42";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// use the timezone name. Example: "UTC", "America/New_York", "Europe/Berlin", etc
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse(input);
// difference in milliseconds
long diffFromNow = System.currentTimeMillis() - date.getTime();
另一种选择(更好的是,IMO),是使用java.time(API 级别 26)或threeten backport(API 级别 see here 如何在 Android 中配置它):
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
ZonedDateTime zdt = LocalDateTime
// parse date/time String
.parse(input, fmt)
// set to a timezone (for UTC, use ZoneOffset.UTC)
.atZone(ZoneId.of("America/New_York"));
// difference in milliseconds
long diffFromNow = ChronoUnit.MILLIS.between(Instant.now(), zdt.toInstant());