Ali*_*lin 35 android date seconds
我在网上尝试了不同的方法,但无法使其正常工作.
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")));
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我可以获得良好格式的两个日期.现在我想找到之间的差异EndDate,并Startdate在几秒钟.
有什么建议?谢谢.
Che*_*mon 104
您可以将日期对象转换为长(1970年1月1日以来的毫秒),然后使用TimeUnit以获取秒数:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
Run Code Online (Sandbox Code Playgroud)
编辑:-Corrected在第二行写入diffInM(i)的变量diffInMs的名称.
只是为使用时间而不是日期的其他开发人员(如我)补充这个答案。
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));
Run Code Online (Sandbox Code Playgroud)
尝试以下方法: -
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";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
44252 次 |
| 最近记录: |