1.得到當前時間
System.currentTimeMillis()
2.計算時差。
用當前的系統時間減去之前保存的系統時間
//之前保存的時間
long beforTime=System.currentTimeMillis();
//現在保存的時間
long nowTime=System.currentTimeMillis();
//計算間隔時間差
long time=nowTime-beforTime;
然後,用時差long值換算成分鐘
//時差判斷
public String timeGap(long time){
if(time>=(1000*60*60*24*30L)){
long monthNum = time/(1000*60*60*24*30L);
return "已離線"+monthNum+"個月";
}else if(time>=(1000*60*60*24)){
long dayNum = time/(1000*60*60*24);
return "已離線"+dayNum+"天";
}else if(time>=(1000*60*60)){
long hourNum = time/(1000*60*60);
return "已離線"+hourNum+"小時";
}else if(time>=(1000*60)){
long minuteNum = time/(1000*60);
return "已離線"+minuteNum+"分鐘";
}else{
return "已離線少於1分鐘";
}
}
3.格式化時間
SimpleDateFormat sDateFormat = new SimpleDateFormat ("yyyy-MM-dd hh:mm:ss");
String date = sDateFormat.format(System.currentTimeMillis());