English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java code to split date time periods

This article shares the Java code for cutting date periods with examples for your reference, the specific content is as follows

/**
 * @author dy
 * @since 2016-09-18 & JDK 1.8.0_91
 */
public class DateCalculate {
  static Logger logger = LoggerFactory.getLogger(DateCalculate.class);
  /**
   * Cutting time period
   *
   * @param dateType Trade type M/D/H/N --More than every month/Every day/Every hour/Every minute
   * @param end  yyyy-MM-@return
   * dd HH:mm:ss-MM-@return
   * public static List<String> cutDate(String dateType, String start, String end) {
   */
  try {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy
      dd HH:mm:ss);-MM-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;
        
          calBegin.add(Calendar.HOUR, 1);break;
        
          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);
    }
  }
}

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like