我尝试了网络周围的不同方法,但无法使其正常工作。

Cursor cursor = sqlite.myDataBase.rawQuery("SELECT StartDate, EndDate FROM Tracks Where Id="+'"'+trackId+'"',null);

SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("StartDate")));
Date endDate = outputFormat.parse(cursor.getString(cursor.getColumnIndex("EndDate")));

这样,我以良好的格式获得两个日期。现在我想找到 EndDateStartdate 片刻之间。

有建议吗?谢谢你。

有帮助吗?

解决方案

您可以将日期对象变成一个长(自1970年1月1日以来的毫秒),然后使用 TimeUnit 获取秒数:

long diffInMs = endDate.getTime() - startDate.getTime();

long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);

编辑: - 校正第二行中写入差异(i)的变量差异的名称。

其他提示

尝试以下方法: -

    public String twoDatesBetweenTime(String oldtime)
    {
        // TODO Auto-generated method stub
        int day = 0;
        int hh = 0;
        int mm = 0;
        try
        {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date oldDate = dateFormat.parse(oldtime);
            Date cDate = new Date();
            Long timeDiff = cDate.getTime() - oldDate.getTime();
            day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
            hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
            mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }
        if(day==0)
        {
            return hh + " hour " + mm + " min";
        }
        else if(hh==0)
        {
            return mm + " min";
        }
        else
        {
            return day + " days " + hh + " hour " + mm + " min";
        }
    }

只是为使用时间而不是日期的其他开发人员(像我一样)补充了这个答案。

Time t1 = new Time();
t1.setToNow();
Thread.sleep(1000);

Time t2 = new Time();
t2.setToNow();

diff = TimeUnit.MILLISECONDS.toSeconds(t2.toMillis(true)-t1.toMillis(true));
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top