简体   繁体   English

如何计算当前日期和字符串文本日期之间的小时数

[英]How to calculate number of hours between current date and an String text date

I am getting a string from service, 2 Nov 2019 07:30 pm , the date is in United States Central Time .我从服务中得到一个字符串, 2 Nov 2019 07:30 pm ,日期是United States Central Time

Now i need to know how much time is remaining between current time and this date.现在我需要知道当前时间和这个日期之间还剩下多少时间。

I am using following code, but this is not giving accurate difference.我正在使用以下代码,但这并没有给出准确的区别。

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();
}

Although it is not clear in your question where you are getting current time from, my guess is that the problem is in the way you are using TimeZone.尽管您的问题不清楚您从哪里获得当前时间,但我的猜测是问题出在您使用 TimeZone 的方式上。 You are setting the TimeZone in the formatter then parsing the date which you say is already in CST.您在格式化程序中设置时区,然后解析您所说的日期已经在 CST 中。

Here is an alternate way you can do the same thing and then compare your results:这是另一种方法,你可以做同样的事情,然后比较你的结果:

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());

String date "2 Nov 2019 07:30 pm" should be parsed this way:字符串日期“2 Nov 2019 07:30 pm”应该这样解析:

new SimpleDateFormat("dd MMM yyyy hh:mm a")

Not this way:不是这样:

new SimpleDateFormat("MMM d yyyy hh:mm a");

Use following code for result使用以下代码获取结果

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

                Date event_date = dateFormat.parse("2 Nov 2019 07:30 pm");
                Date current_date = new Date();
                long diff = event_date.getTime() - current_date.getTime();
                long Days = diff / (24 * 60 * 60 * 1000);
                long Hours = diff / (60 * 60 * 1000) % 24;
                long Minutes = diff / (60 * 1000) % 60;
                long Seconds = diff / 1000 % 60;

                Log.i(TAG, Hours + "," + Minutes + "," + Seconds);

java.time and ThreeTenABP java.time 和 ThreeTenABP

This will work on your Android API level:这将适用于您的 Android API 级别:

    DateTimeFormatter formatter = new DateTimeFormatterBuilder()
            .appendPattern("d MMM uuuu hh:mm ")
            .parseCaseInsensitive()
            .appendPattern("a")
            .toFormatter(Locale.US);
    ZoneId zone = ZoneId.of("America/Chicago");

    ZonedDateTime currentDateTime = ZonedDateTime.now(zone);

    String dateTimeString = "2 Nov 2019 07:30 pm";
    ZonedDateTime dateTime = LocalDateTime.parse(dateTimeString, formatter)
            .atZone(zone);

    long diffInHours = ChronoUnit.HOURS.between(currentDateTime, dateTime);
    System.out.println("Difference in hours: " + diffInHours);

When I ran this snippet just now, the output was:当我刚才运行这个片段时,output 是:

Difference in hours: 541小时差异:541

I am using java.time, the modern Java date and time API.我正在使用 java.time,现代 Java 日期和时间 API。 It's much nicer to work with than the old and poorly designed Date and SimpleDateFormat .它比旧的和设计不佳的DateSimpleDateFormat更好用。 On one hand parsing lowercase am and pm requires a little more code lines (since they are normally in uppercase in US locale), on the other hand java.time validates more strictly, which is always good.一方面解析小写的ampm需要更多的代码行(因为它们在美国语言环境中通常是大写的),另一方面 java.time 验证更严格,这总是好的。 Advantages we get for free include: We need no time zone conversions, we can do everything in Central Time.我们免费获得的优势包括:我们不需要时区转换,我们可以在中央时间做任何事情。 The calculation of the difference in hours is built in, just requires one method call.以小时为单位的计算是内置的,只需要一个方法调用。

Specify locale for your formatter, or it will break when some day your code runs on a JVM with a non-English default locale.为您的格式化程序指定语言环境,否则当您的代码在具有非英语默认语言环境的 JVM 上运行时,它将中断。 Specify US Central Time as America/Chicago.将美国中部时间指定为 America/Chicago。 Always use this region/city format for time zones.始终使用此区域/城市格式作为时区。 CST is deprecated and also lying since it gives you CDT at this time of year. CST 已被弃用并且还在撒谎,因为它会在每年的这个时候为您提供 CDT。

Question: Doesn't java.time require Android API level 26 or higher?问:java.time 是否需要 Android API 26 级或更高级别?

java.time works nicely on both older and newer Android devices. java.time 适用于较旧和较新的 Android 设备。 It just requires at least Java 6 .它只需要至少Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.在 Java 8 及更高版本以及更新的 Android 设备(来自 API 级别 26)中,现代 ZDB9734A 内置23871083ACE16。
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).在非 Android Java 6 和 7 中,获得 ThreeTen Backport,现代类的后向端口(JSR 310 的 ThreeTen;参见底部的链接)。
  • On (older) Android use the Android edition of ThreeTen Backport.在(旧版)Android 上,使用 ThreeTen Backport 的 Android 版本。 It's called ThreeTenABP.它被称为 ThreeTenABP。 And make sure you import the date and time classes from org.threeten.bp with subpackages.并确保从带有子包的org.threeten.bp导入日期和时间类。

Links链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 计算当前日期和过去日期之间的差额 - Calculate the difference between Current Date and Past Date 如何计算饼图中显示的日期与当前日期之间的差异 - How to calculate the difference between the dates shown in the piechart with the current date 如何在年龄计算器中计算输入日期和当前日期之间的确切天数? - How to calculate the exact days in Age Calculator between the date entered & the current date? 如何比较日期字符串和当前日期? - How to compare a date string to current date? 如何将 localdatetime 与当前日期进行比较,包括 java 中的小时数 - how compare localdatetime with current date including hours in java 如何使用Java计算数据库与当前日期之间的天数差异 - How to calculate difference in days between the one from database and current date using java 如何计算从给定日期算起的X天数? - How to calculate the date that is X number of week days from a given date? 如何在Java中将当前日期转换为特定数字 - How to transform current Date in a specific Number in Java 如何计算通过android中的日期选择器选择的两个日期之间的天数 - How to calculate the number of days between two dates selected through date Picker in android 如何在小时,分钟和秒的时间内将字符串转换为Date对象 - How to convert a String to a Date object for hours, minutes, and seconds
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM