一. 介绍
有时我们需要把某个时间范围进行时间段的切分,故此记录实现方式,欢迎大神点评帮忙优化和精简!
二. 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| package com.vanbrother.p2p.service.common.utils.hessian;
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List;
public class DateUtils {
public static String YEAR_REGEX = "^\\d{4}$"; public static String MONTH_REGEX = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}$"; public static String DATE_REGEX = "^\\d{4}(\\-|\\/|\\.)\\d{1,2}\\1\\d{1,2}$";
public static String format(Date date, String pattern) { SimpleDateFormat sd = new SimpleDateFormat(pattern); return sd.format(date); }
public static Date parse(String date, String pattern) throws ParseException { SimpleDateFormat sd = new SimpleDateFormat(pattern); try { return sd.parse(date); } catch (ParseException e) { throw e; } }
public static List<String> sliceUpDateRange(String startDate, String endDate) { List<String> rs = new ArrayList<>(); try { int dt = Calendar.DATE; String pattern = "yyyy-MM-dd"; if(startDate.matches(YEAR_REGEX)) { pattern = "yyyy"; dt = Calendar.YEAR; } else if(startDate.matches(MONTH_REGEX)) { pattern = "yyyy-MM"; dt = Calendar.MONTH; } else if(startDate.matches(DATE_REGEX)) { pattern = "yyyy-MM-dd"; dt = Calendar.DATE; } Calendar sc = Calendar.getInstance(); Calendar ec = Calendar.getInstance(); sc.setTime(parse(startDate, pattern)); ec.setTime(parse(endDate, pattern)); while(sc.compareTo(ec) < 1){ rs.add(format(sc.getTime(), pattern)); sc.add(dt, 1); } } catch (ParseException e) { e.printStackTrace(); } return rs; } }
|