android定时器开发中如何实现不受时差的影响
程序员文章站
2022-04-07 19:38:06
android定时器开发中如何实现不受时差的影响。
1、使用android自带的定时器实现:其中mInquiryTimeLongTv是一个TextView控件,mInterrog...
android定时器开发中如何实现不受时差的影响。
1、使用android自带的定时器实现:其中mInquiryTimeLongTv是一个TextView控件,mInterrogationTime是初始为0的一个变量 。
new Timer.schedule(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { mInquiryTimeLongTv.setText(DateUtil.getFormatDate(mInterrogationTime)); mInterrogationTime++; } }); } }, 1000, 1000);
2、时间转换:
/** * 根据秒获取格式:00:00:00字符串 * * @param seconds * @return 00:00:00 */ public static String getFormatDate(long seconds) { String mInquiryDate; seconds++; long mDiff = seconds * 1000; long mDay = mDiff / (24 * 60 * 60 * 1000); long mHour = (mDiff / (60 * 60 * 1000) - mDay * 24); long mMin = ((mDiff / (60 * 1000)) - mDay * 24 * 60 - mHour * 60); long mSecond = (mDiff / 1000 - mDay * 24 * 60 * 60 - mHour * 60 * 60 - mMin * 60); if (mHour > 0) { String secondStr = getTimeFormat(mSecond); String minStr = getTimeFormat(mMin); String hourStr = getTimeFormat(mHour); mInquiryDate = hourStr + ":" + minStr + ":" + secondStr; } else if (mMin > 0) { String secondStr = getTimeFormat(mSecond); String minStr = getTimeFormat(mMin); mInquiryDate = "00:" + minStr + ":" + secondStr; } else if (mSecond > 0) { String secondStr = getTimeFormat(mSecond); mInquiryDate = "00:00:" + secondStr; } else { mInquiryDate = "00:00:00"; } return mInquiryDate; } private static String getTimeFormat(long time) { String timeFormat; if (time < 10) { timeFormat = "0" + time; } else { timeFormat = time + ""; } return timeFormat; }