public class MainActivity extends Activity { private String str; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getTime(); getJudgetoDay();//判断是否是今天 getJudgeYesterday();//判断是否是昨天 } public void getJudgeYesterday() { try { boolean flag = IsYesterday(str); if (flag == true) {//是昨天 //TODO } else {//不是昨天 //TODO } } catch (ParseException e) { e.printStackTrace(); } } public void getJudgetoDay() { try { boolean flag = IsToday(str); if (flag == true) {//是今天 //TODO } else {//不是今天 //TODO } } catch (ParseException e) { e.printStackTrace(); } } private void getTime() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//得到当前的时间 Date curDate = new Date(System.currentTimeMillis()); str = formatter.format(curDate); } /** * 判断是否为今天(效率比较高) * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return true今天 false不是 * @throws ParseException */ public static boolean IsToday(String day) throws ParseException { Calendar pre = Calendar.getInstance(); Date predate = new Date(System.currentTimeMillis()); pre.setTime(predate); Calendar cal = Calendar.getInstance(); Date date = getDateFormat().parse(day); cal.setTime(date); if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) { int diffDay = cal.get(Calendar.DAY_OF_YEAR) - pre.get(Calendar.DAY_OF_YEAR); if (diffDay == 0) { return true; } } return false; } /** * 判断是否为昨天(效率比较高) * * @param day 传入的 时间 "2016-06-28 10:10:30" "2016-06-28" 都可以 * @return true今天 false不是 * @throws ParseException */ public static boolean IsYesterday(String day) throws ParseException { Calendar pre = Calendar.getInstance(); Date predate = new Date(System.currentTimeMillis()); pre.setTime(predate); Calendar cal = Calendar.getInstance(); Date date = getDateFormat().parse(day); cal.setTime(date); if (cal.get(Calendar.YEAR) == (pre.get(Calendar.YEAR))) { int diffDay = cal.get(Calendar.DAY_OF_YEAR) - pre.get(Calendar.DAY_OF_YEAR); if (diffDay == -1) { return true; } } return false; } public static SimpleDateFormat getDateFormat() { if (null == DateLocal.get()) { DateLocal.set(new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA)); } return DateLocal.get(); } private static ThreadLocal<SimpleDateFormat> DateLocal = new ThreadLocal<SimpleDateFormat>(); }
Android 判断获取的时间是否是今天、昨天
最新推荐文章于 2024-12-21 11:53:34 发布