根據當前時間獲取當前周的開始、結束時間(週一到週日)
阿新 • • 發佈:2019-01-31
專案開發中,碰見每週更新三道題的需求,不能多於三道題
package test; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; public class Test { // 獲得本週一與當前日期相差的天數 public static int getMondayPlus() { Calendar cd = Calendar.getInstance(); int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK); //由於Calendar提供的都是以星期日作為週一的開始時間 if (dayOfWeek == 1) { return -6; } else { return 2 - dayOfWeek; } } // 獲得當前周- 週一的日期 public static Long getCurrentMonday() { int mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new GregorianCalendar(); currentDate.add(GregorianCalendar.DATE, mondayPlus); Date monday = currentDate.getTime(); return monday.getTime(); } // 獲得當前周- 週日 的日期 public static Long getPreviousSunday() { int mondayPlus = getMondayPlus(); GregorianCalendar currentDate = new GregorianCalendar(); currentDate.add(GregorianCalendar.DATE, mondayPlus +6); Date monday = currentDate.getTime(); return monday.getTime(); } public static void main(String[] args) throws Exception { Long start = Test.getCurrentMonday(); Long end = Test.getPreviousSunday(); //模擬查出最新的3個 List<String> list = new ArrayList<String>(); list.add("2018-07-30 23:30:01"); list.add("2018-07-30 14:30:27"); list.add("2018-07-31 13:50:55"); boolean flag = false; for(int i=0;i<list.size();i++){ Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(list.get(i).toString()); if(date.getTime() > start && date.getTime() < end){}else{flag = true; break;} } if(flag){ System.out.println("可以建立"); }else{ System.out.println("不能再建立"); } } }