java - 如何计算当前日期和字符串文本日期之间的小时数
问题描述
我从服务中得到一个字符串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();
}
解决方案
尽管您的问题不清楚您从哪里获得当前时间,但我的猜测是问题出在您使用 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());
推荐阅读
- jquery - 内容更新时跳转页面(从较长的内容到较短的内容)
- c++ - 减少第三方库的导出符号
- sql - 并发失败后接收电子邮件的最佳方式(sql - 触发器 - 应用程序)
- reactjs - npm start 在新的 React 项目中不起作用
- spring - Spring mongodb,将文档保存两次:在它自己的集合中和嵌入到其他集合中
- python-3.x - 编写递归函数列出parts.txt的所有路径
- apache-spark - PySpark 根据列键将 DataFrame 拆分为多个帧,并在每个帧上训练一个 ML lib 模型
- asp.net-mvc - 在下拉列表中选择默认值并传递 id MVC 下拉列表
- python - Python smbus 读取数据
- android - Android:onUpgrade 后第一次尝试执行 getWritableDatabase() 时出现 SQLite“数据库锁定”异常