在计算android中的时间差异时得到不同的结果

时间:2014-03-20 10:03:24

标签: android datetime

我从两个EditTexts中获取时间值以及花费的总时间,但这不能按预期工作。任何人都可以帮助我吗?

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

1 个答案:

答案 0 :(得分:0)

哦,我会给你一个例子,我的代码中的一个制作我采取时间的差异当前和从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;
    }