【问题标题】:Not able to get difference between two datetime?无法获得两个日期时间之间的差异?
【发布时间】:2014-04-10 08:13:05
【问题描述】:

请检查以下代码。我试图获得差异,但每次都得到 0。 谁能指出下面的代码有什么问题?

SimpleDateFormat sDateFormat = new SimpleDateFormat("hh:mm:ss dd/mm/yyyy");
try {

    long d1 = sDateFormat.parse("10:04:00 04/04/2014").getTime();
    long d2 = sDateFormat.parse("10:09:00 04/04/2014").getTime();

    long difference = d2 - d1;

    Log.i(TAG,">> Difference = "+difference);

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

【问题讨论】:

  • 你也可以使用joda api
  • ur d1 和 d2 日期相同还是不同?
  • @Wizard,两者的时间不同
  • @Hitendra 你试过这个link

标签: java android date simpledateformat


【解决方案1】:

您的格式化程序不适合使用的日期格式。

试试:

new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");

【讨论】:

    【解决方案2】:

    SimpleDateFormat 的Android 开发者文档中,您可以看到M 代表Monthm 代表minute...

    M   month in year   (Text)      M:1 MM:01 MMM:Jan MMMM:January MMMMM:J
    m   minute in hour  (Number)    30
    

    因此,您应该从此更改日期格式...

    hh:mm:ss dd/mm/yyyy
    

    到这个...

    hh:mm:ss dd/MM/yyyy
    

    我希望这个格式更正能解决你的问题。

    【讨论】:

      【解决方案3】:

      你的格式hh:mm:ss dd/mm/yyyy有两个问题:

      1. h 用于 12 小时时间格式,即带有 AM/PM 标记的时间格式,日期时间字符串不是这种情况。您需要使用 H,它用于 24 小时时间格式。
      2. m 一个月未使用。一个月,你需要使用M

      除此之外,旧的日期时间 API(java.util 日期时间类型及其格式化 API,SimpleDateFormat)已经过时且容易出错。建议完全停止使用它们并切换到java.timemodern date-time API*

      使用现代日期时间 API 的演示:

      import java.time.LocalDateTime;
      import java.time.format.DateTimeFormatter;
      import java.time.temporal.ChronoUnit;
      
      public class Main {
          public static void main(String args[]) {
              DateTimeFormatter dtf = DateTimeFormatter.ofPattern("H:m:s d/M/u");
              LocalDateTime start = LocalDateTime.parse("10:04:00 04/04/2014", dtf);
              LocalDateTime end = LocalDateTime.parse("10:09:00 04/04/2014", dtf);
              long diff = ChronoUnit.MILLIS.between(start, end);
              System.out.println(diff);
          }
      }
      

      输出:

      300000
      

      Trail: Date Time 了解有关 modern date-time API* 的更多信息。


      * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 和 7 . 如果您正在为一个 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        相关资源
        最近更新 更多