一:this
//若是超過此時間,則不能進入程序 if (isExpiredLocal(2013, 7, 07)) { Toast.makeText(this, "EXPIRED!", Toast.LENGTH_SHORT).show(); this.finish();(this爲進入程序的Activity) return; } /** * 判斷本機日期是否超過 指定的日期, * * @param year * @param month * @param day * @return */ public static boolean isExpiredLocal(int year, int month, int day) { Calendar endtime = Calendar.getInstance(); endtime.set(year, month - 1, day); Calendar currenttime = Calendar.getInstance(); return currenttime.after(endtime); }
二:spa
//正常 private static final int TRIAL = 2; //即將過時 private static final int EXPIRE_SOON= 1; //過時 private static final int BOMB = 0; // 時間炸彈 if (isExpiredLocal(2) == TRIAL) { // 正常時的操做 } else if (isExpiredLocal(2) == EXPIRE_SOON) { // 即將過時時的操做 } else if (isExpiredLocal(2) == BOMB) { // 過時時的操做 } /** * 判斷本機日期是否超過 指定的日期, * * @return */ public int isExpiredLocal(int months) { // 建立將要寫入時間炸彈日期的文件路徑 String filePath = "/mnt/sdcard/Dreye"; String dirPath = "/mnt/sdcard/Dreye/timeBomb.txt"; // 若是文件不存在 if (!new File(dirPath).exists()) { // 將時間炸彈的日期寫入「timeBomb.txt」文件,參數2表示當前時期加上2個月以後的時間,即:兩個月後 String sdate = nDaysAftertoday(months); FileUtil.writeSd(filePath, dirPath, sdate); } // 從文件中讀取時間炸彈的日期 String timeBomb = FileUtil.readSd(dirPath); Date d = new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("今天的日期:" + df.format(d)); String currenttime = df.format(d); int betweenDays = nDaysBetweenTwoDate(currenttime, timeBomb); //即將到期 if ((betweenDays < 10) & (betweenDays > 0)) { return EXPIRE_SOON; //到期 } else if ((betweenDays == 0)|| (betweenDays < 0)) { return BOMB; }
//正常
return TRIAL; } /** * 獲取n個月後的日期 * * @param nMonths * @return yyyy-MM-dd */ public String nDaysAftertoday(int nMonths) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", this .getResources().getConfiguration().locale); Calendar rightNow = Calendar.getInstance(); // rightNow.add(Calendar.DAY_OF_MONTH,-1); rightNow.add(Calendar.MONTH, +nMonths); return df.format(rightNow.getTime()); } /** * 計算兩個日期相隔的天數 * @param firstString * @param secondString * @return 相隔的天數 */ public int nDaysBetweenTwoDate(String firstString, String secondString) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date firstDate = null; Date secondDate = null; try { firstDate = df.parse(firstString); secondDate = df.parse(secondString); } catch (Exception e) { // 日期型字符串格式錯誤 } int nDay = (int) ((secondDate.getTime() - firstDate.getTime()) / (24 * 60 * 60 * 1000)); return nDay; }