【问题标题】:How to find the difference between two times in Android / Java? [duplicate]如何在Android / Java中找到两次之间的差异? [复制]
【发布时间】:2012-12-25 04:33:19
【问题描述】:

可能重复:
Calculating the Difference Between Two Java Date Instances

我在 HH:MM:SS 格式的字符串数据类型的两个文本框中有两个日期值。我怎样才能找到它们之间的差异并在 HH:MM:SS 中得到结果?请帮助我...尽快。 ...!

【问题讨论】:

  • 你怎么知道它不起作用?样本/预期输入/输出?
  • 什么不起作用?他们不是应该进行比较吗?代码看起来完全没问题。

标签: java android datetime timertask date-difference


【解决方案1】:

试试这个:

     SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
     format.setTimeZone(TimeZone.getTimeZone("UTC"));
     try {
         Date date1 = (Date) format.parse("4:15:20");
         Date date2 = (Date) format.parse("2:30:30");
         //time difference in milliseconds
         long timeDiff = date1.getTime() - date2.getTime(); 
         //new date object with time difference
         Date diffDate = new Date(timeDiff); 
         //formatted date string
         String timeDiffString = format.format(diffDate); 
         System.out.println("Time Diff = "+ timeDiffString );
     } catch (ParseException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }

以上代码有一定的限制。其他正确的方法可能是在字符串中手动转换长时差值,如下所示:

     long timeDiffSecs = timeDiff/1000;
     String timeDiffString = timeDiffSecs/3600+":"+
                             (timeDiffSecs%3600)/60+":"+
                             (timeDiffSecs%3600)%60;
     System.out.println("Time Diff = "+ timeDiffString);

【讨论】:

  • 它不工作...朋友..:(
  • @jims 什么不起作用?一定要突出这个问题。以上代码 sn-ps 都是工作代码。我在发布之前验证了它。第一个有一些我已经提到的限制。
  • 第二种方案最好,谢谢。
【解决方案2】:

您拥有的代码将为您提供所列日期之间的毫秒数差异。答案可能是简单地除以 1000 得到秒数。

【讨论】:

  • 先生,我有两次 HH:MM:SS 格式,现在我想从 time2 中减去 time1 并希望得到 HH:MM:SS 格式的结果...请您帮忙?
【解决方案3】:

首先将字符串日期转换为简单的日期格式

public String getconvertdate1(String date)
{
    DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
    Date parsed = new Date();
    try
    {
        parsed = inputFormat.parse(date);
    }
    catch (ParseException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String outputText = outputFormat.format(parsed);
    return outputText;
}

//现在可以对日期做任何事情。

 long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
 long days = diff / (24 * 60 * 60 * 1000);// you get day difference between

并使用 simpledateFormate 配置 HH:MM:SS

【讨论】:

  • 先生,问题是我这两个时间都是字符串格式..请帮助我..:(
  • @jims 我已经编辑了我的答案你日期格式字符串首先转换它们...
  • 12-25 09:00:56.537: W/System.err(1642): java.lang.ClassCastException: java.util.Date 不能转换为 java.sql.Date.... .........
  • ctr+shift+O 按下并选择 java.util.Date 而不是 java.sql.Date。
  • tnx altaf...完成...谢谢...:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 2011-06-01
  • 2016-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多