1 import java.text.ParseException;
2 import java.text.SimpleDateFormat;
3 import java.util.Calendar;
4 import java.util.Date;
5
6 /**
7 * 日期工具
8 * @author hp
9 *
10 */
11 public class DateUtil {
12
13 public static void main(String[] args) {
14 try {
15 String[] xunArr = getLastXun(new Date());
16 System.out.println(xunArr[0] + "," + xunArr[1]);
17 } catch (Exception e) {
18 e.printStackTrace();
19 }
20 }
21
22 /**
23 * 根据给定日期判断上一旬的开始结束日期
24 * @param nowDate
25 * @return
26 * @throws ParseException
27 */
28 public static String[] getLastXun(Date nowDate) throws ParseException{
29 //存放上旬开始结束日期
30 String[] xunArr = new String[2];
31
32 SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
33 SimpleDateFormat monthFormat = new SimpleDateFormat("yyyyMM");
34 SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
35
36 int day = Integer.parseInt(dayFormat.format(nowDate));
37 if(day <= 10){
38 //如果是上旬,查找上个月的下旬
39 Calendar calendar = Calendar.getInstance();
40 calendar.add(Calendar.MONTH, -1);
41 xunArr[0] = monthFormat.format(calendar.getTime())+"21";
42
43 calendar.setTime(format.parse((monthFormat.format(nowDate)+"01")));
44 calendar.add(Calendar.DATE, -1);
45 xunArr[1] = format.format(calendar.getTime());
46 }else if(day <= 20){
47 //如果是中旬,查找上旬
48 xunArr[0] = monthFormat.format(nowDate)+"01";
49 xunArr[1] = monthFormat.format(nowDate)+"10";
50 }else{
51 //如果是下旬,查找中旬
52 xunArr[0] = monthFormat.format(nowDate)+"11";
53 xunArr[1] = monthFormat.format(nowDate)+"20";
54 }
55
56 return xunArr;
57 }
58 }