【问题标题】:Getting different result while calculating difference of time in android在android中计算时间差时得到不同的结果
【发布时间】:2014-03-20 10:03:23
【问题描述】:

我正在从两个 EditText 获取时间值以及花费的总时间,但这没有按预期工作。任何人都可以帮助我吗?

      SimpleDateFormat format = new SimpleDateFormat("HH:mm");

    try {
        dateOne = format.parse(strFromVessel);
        dateTwo = format.parse(strToVessel);
        System.out.println("date1" + dateOne + "date2" + dateTwo);


        long diff = Math.abs(dateTwo.getTime() - dateOne.getTime());
        System.out.println("diff"+diff);
        System.out.println("dateTwo.getTime()"+dateTwo.getTime());
        System.out.println("dateo.getTime()"+dateOne.getTime());

        long Hours = diff/(1000 * 60 * 60);
        long Mins = diff % (1000*60*60);

        String difference = Hours + ":" + Mins; 
        System.out.println("long"+difference);

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

【问题讨论】:

  • 你的期望是什么,结果是什么
  • @GopalRao 不正确
  • @Mark Buikema 我得到 1:60000 作为 13:57 和 14:58 差异的输出

标签: android datetime


【解决方案1】:

哦,我会给你一个例子,在我的代码中,我使用当前时间的差异,从 1970 年 1 月 1 日开始,我像这样计算时间差异,这可能会帮助你只是把你的时间而不是我的时间休息代码原样使用

 Calendar cal = Calendar.getInstance();
    Date currentLocalTime = cal.getTime();
    DateFormat date = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");  
    date.setTimeZone(TimeZone.getTimeZone("GMT")); 
    String localTime = date.format(currentLocalTime); 

    long currenttime = Constant.retunlongdate(localTime);
    long fixtimejan = Constant.retunlongdate("01/01/1970 00:00:00 AM");

    long nTimeStamp = (currenttime - fixtimejan)/1000;
    System.out.println("and result is == " + nTimeStamp);

 public static long retunlongdate(String givenDateString)
        {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"); 

        long timeInMilliseconds=0;
        try {
            Date mDate =sdf.parse(givenDateString);
              timeInMilliseconds = mDate.getTime();
            System.out.println("Date in milli :: " + timeInMilliseconds);
            return timeInMilliseconds;
        } catch (ParseException e) {
                    e.printStackTrace();
        } catch (java.text.ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
        return timeInMilliseconds;
    }

【讨论】:

  • 只有我想要的时间差异
  • 是的,但你必须从亲爱的 longtimemillis 计算它,我的方法也是这样
  • 但问题是我没有得到预期的结果
  • 它的错误方法是你使用 pooja 因为时间必须与它一起提供所有信息然后只有你不时采取差异
  • 只要明白如果你花时间 12.00 今天日期和第二个日期是 12.01 的 tommarow 那么时间差异只能是 1 分钟吗?不,这将是 1 天 1 分钟的时间了解我试图告诉的内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-13
  • 2020-02-14
相关资源
最近更新 更多