java分割日期时间段代码

时间:2021-07-30 15:32:48

本文实例为大家分享了java切割日期时间段代码,供大家参考,具体内容如下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * @author dy
 * @since 2016-09-18 & JDK 1.8.0_91
 */
public class DateCalculate {
  static Logger logger = LoggerFactory.getLogger(DateCalculate.class);
 
  /**
   * 切割时间段
   *
   * @param dateType 交易类型 M/D/H/N -->每月/每天/每小时/每分钟
   * @param start yyyy-MM-dd HH:mm:ss
   * @param end  yyyy-MM-dd HH:mm:ss
   * @return
   */
  public static List<String> cutDate(String dateType, String start, String end) {
    try {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date dBegin = sdf.parse(start);
      Date dEnd = sdf.parse(end);
      return findDates(dateType, dBegin, dEnd);
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return null;
  }
 
  public static List<String> findDates(String dateType, Date dBegin, Date dEnd) throws Exception {
    List<String> listDate = new ArrayList<>();
    Calendar calBegin = Calendar.getInstance();
    calBegin.setTime(dBegin);
    Calendar calEnd = Calendar.getInstance();
    calEnd.setTime(dEnd);
    while (calEnd.after(calBegin)) {
      switch (dateType) {
        case "M":
          calBegin.add(Calendar.MONTH, 1);
          break;
        case "D":
          calBegin.add(Calendar.DAY_OF_YEAR, 1);break;
        case "H":
          calBegin.add(Calendar.HOUR, 1);break;
        case "N":
          calBegin.add(Calendar.SECOND, 1);break;
      }
      if (calEnd.after(calBegin))
        listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calBegin.getTime()));
      else
        listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calEnd.getTime()));
    }
    return listDate;
  }
 
 
  public static void main(String[] args) {
    String start = "2016-02-01 00:00:00";
    String end = "2016-03-02 00:00:00";
    List<String> list = cutDate("D", start, end);
    for (String str :list){
      System.out.println(str);
    }
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。