一些Java的公用方法:
1:獲取當前時間 2:判斷當前時間是否在時間date2之前
3:比較時間大小
4:獲取某個時間的前n個小時
5:返回某個字符串時間的Calendar對象
6:判斷兩個時間段是否有重疊
7:獲取前后n周的周x
8:獲取過去12個月份yyyy-MM
1.獲取當前時間
public static String getToday() { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = new Date(); String today = formatter.format(date); return today; }
2.判斷當前時間是否在時間date2之前
/** * 時間格式 2018-4-21 16:16:34 * @param date2 * @return */ public static boolean isDateBefore(String date2) { try { Date date1 = new Date(); DateFormat df = DateFormat.getDateTimeInstance(); return date1.before(df.parse(date2)); } catch (ParseException e) { return false; } }
3.比較時間大小
// 比較時間大小 date1<date2 true public static boolean compareMinDate(String date1, String date2) throws ParseException { Date d1 = convertToCalendar(date1).getTime(); Date d2 = convertToCalendar(date2).getTime(); return d1.before(d2); }
4.獲取某個時間的前n個小時
// 獲取某個時間的前n小時 public static String getBeforeNHour(int n, String nowTime, String pattern) throws Exception { SimpleDateFormat sdf = new SimpleDateFormat(pattern); Date date = null; date = sdf.parse(nowTime); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.HOUR, n); return sdf.format(cal.getTime()); }
5.返回某個字符串時間的Calendar對象
// 返回某個字符串時間的Calendar對象 public static Calendar convertToCalendar(String date) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d = sdf.parse(date); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(d); return calendar; }
6.判斷兩個時間段是否有重疊
2個時間段: begin2, end2 beginTime, endTime 公式: begin2 <= endTime and end2 >= beginTime if (compareHours(begin2, endTime)>0 && compareHours(beginTime, end2)>0) { errorMsg = "重疊了"; break; }
7.獲取前后n周的周x
private String getLastMonday() { Calendar cal = Calendar.getInstance(); // n為推遲的周數,1本周,-1向前推遲一周,2下周,依次類推 int n = -1; String monday; cal.add(Calendar.DATE, n * 7); // 想周幾,這里就傳幾Calendar.MONDAY(TUESDAY...) cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); monday = new SimpleDateFormat("yyyy-MM-dd").format(cal.getTime()); return monday; }
8.獲取過去12個月份yyyy-MM
private String[] getLast12Months(){ DecimalFormat df = new DecimalFormat("00"); String[] last12Months = new String[12]; Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)+1); //先+1,才能把本月進去 for(int i=0; i<12; i++){ cal.set(Calendar.MONTH, cal.get(Calendar.MONTH)-1); //逐次往前推1個月 last12Months[i] = cal.get(Calendar.YEAR)+ "-" + df.format(cal.get(Calendar.MONTH)+1); } return last12Months; }