首页 > 解决方案 > 如何计算当前日期和字符串文本日期之间的小时数

问题描述

我从服务中得到一个字符串2 Nov 2019 07:30 pm,日期在United States Central Time.

现在我需要知道当前时间和这个日期之间还剩下多少时间。

我正在使用以下代码,但这并没有给出准确的区别。

SimpleDateFormat ticketDateFormat = new SimpleDateFormat("MMM d yyyy hh:mm a");
Date parsedDate= null;
try {
    parsedDate= ticketDateFormat.parse(dateTimeString);

    DateFormat formatter = new SimpleDateFormat("MMM d yyyy hh:mm a");
    TimeZone timeZone = TimeZone.getTimeZone("CST");
    formatter.setTimeZone(timeZone);


    parsedDate= ticketDateFormat.parse(formatter.format(parsedDate));


    long totalTimeRemainingInMillis= Math.abs(currentDateTime.getTime()- (parsedDate.getTime()));
    long diffInHours = TimeUnit.MILLISECONDS.toHours(totalTimeRemainingInMillis);



} catch (ParseException e) {
    e.printStackTrace();
}

标签: javaandroidsimpledateformatandroid-date

解决方案


尽管您的问题不清楚您从哪里获得当前时间,但我的猜测是问题出在您使用 TimeZone 的方式上。您在格式化程序中设置时区,然后解析您所说的日期已经在 CST 中。

这是另一种方法,你可以做同样的事情,然后比较你的结果:

LocalDateTime dateTime = LocalDateTime.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("LLL d yyyy hh:mm a");
LocalDateTime parse = LocalDateTime.parse("Nov 2 2019 07:30 PM", fmt);
System.out.println(Duration.between(dateTime, parse).toHours());

推荐阅读