import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.WordUtils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.ResolverStyle;
import java.time.temporal.*;
import java.util.*;
import java.util.stream.Stream;
@Slf4j
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
private DateUtils() {
}
public static final String PATTERN_UUUU_MM_DD_HH_MM_SS = "uuuu-MM-dd HH:mm:ss";
public static final String PATTERN_UUUUMMDDHHMMSS = "uuuuMMddHHmmss";
public static final String PATTERN_UUUU_MM_DD_HH_MM = "uuuu-MM-dd HH:mm";
public static final String PATTERN_UUUU_MM_DD = "uuuu-MM-dd";
public static final String PATTERN_UUUU_MM = "uuuu-MM";
public static final String PATTERN_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String PATTERN_YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static final String PATTERN_YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static final String PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String PATTERN_YYYY_MM = "yyyy-MM";
public static final String PATTERN_HH_MM_SS = "HH:mm:ss";
public static final String PATTERN_HH_MM = "HH:mm";
private static final Locale DEFAULT_LOCALE;
private static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER;
public static final ZoneId SYSTEM_ZONE_ID;
public static final ZoneOffset SYSTEM_ZONE_OFFSET;
public static final ResolverStyle DEFAULT_RESOLVER_STYLE;
static {
DEFAULT_LOCALE = Locale.ENGLISH;
DEFAULT_DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(PATTERN_UUUU_MM_DD_HH_MM_SS, DEFAULT_LOCALE);
SYSTEM_ZONE_ID = ZoneId.systemDefault();
SYSTEM_ZONE_OFFSET = OffsetDateTime.now(SYSTEM_ZONE_ID).getOffset();
DEFAULT_RESOLVER_STYLE = ResolverStyle.STRICT;
}
public static String defaultDatePattern = PATTERN_YYYY_MM_DD_HH_MM_SS;
public static String defaultLocalDatePattern = PATTERN_UUUU_MM_DD;
public static String defaultLocalDateTimePattern = PATTERN_YYYY_MM_DD_HH_MM_SS;
public static String defaultLocalTimePattern = PATTERN_HH_MM_SS;
public static DateTimeFormatterBuilder getFormatterBuilder(@NotNull String pattern, Map<TemporalField, Long> fieldValueMap) {
DateTimeFormatterBuilder formatterBuilder = new DateTimeFormatterBuilder().appendPattern(pattern);
TemporalField maybeExistTemporalField = ChronoField.YEAR;
if (!pattern.toLowerCase().contains("y") && fieldValueMap.containsKey(maybeExistTemporalField)) {
formatterBuilder.parseDefaulting(maybeExistTemporalField, fieldValueMap.get(maybeExistTemporalField));
fieldValueMap.remove(maybeExistTemporalField);
}
maybeExistTemporalField = ChronoField.MONTH_OF_YEAR;
if (!pattern.contains("M") && !pattern.contains("L") && fieldValueMap.containsKey(maybeExistTemporalField)) {
formatterBuilder.parseDefaulting(maybeExistTemporalField, fieldValueMap.get(maybeExistTemporalField));
fieldValueMap.remove(maybeExistTemporalField);
}
maybeExistTemporalField = ChronoField.DAY_OF_MONTH;
if (!pattern.toLowerCase().contains("d") && !pattern.contains("F") && fieldValueMap.containsKey(maybeExistTemporalField)) {
formatterBuilder.parseDefaulting(maybeExistTemporalField, fieldValueMap.get(maybeExistTemporalField));
fieldValueMap.remove(maybeExistTemporalField);
}
for (TemporalField temporalField : fieldValueMap.keySet()) {
formatterBuilder.parseDefaulting(temporalField, fieldValueMap.get(temporalField));
}
return formatterBuilder;
}
public static DateTimeFormatter getDefaultFormatter(@NotNull String pattern, Locale locale, ZoneId zoneId) {
Map<TemporalField, Long> fieldValueMap = new HashMap<>();
fieldValueMap.put(ChronoField.YEAR, 1970L);
fieldValueMap.put(ChronoField.MONTH_OF_YEAR, 1L);
fieldValueMap.put(ChronoField.DAY_OF_MONTH, 1L);
fieldValueMap.put(ChronoField.HOUR_OF_DAY, 0L);
fieldValueMap.put(ChronoField.MINUTE_OF_HOUR, 0L);
fieldValueMap.put(ChronoField.SECOND_OF_MINUTE, 0L);
fieldValueMap.put(ChronoField.MILLI_OF_SECOND, 0L);
DateTimeFormatter dateTimeFormatter;
DateTimeFormatterBuilder formatterBuilder = getFormatterBuilder(pattern, fieldValueMap);
if (locale != null) {
dateTimeFormatter = formatterBuilder.toFormatter(locale);
} else {
dateTimeFormatter = formatterBuilder.toFormatter();
}
dateTimeFormatter.withResolverStyle(DEFAULT_RESOLVER_STYLE);
if (zoneId != null) {
dateTimeFormatter.withZone(zoneId);
}
return dateTimeFormatter;
}
public static DateTimeFormatter getDefaultFormatter(@NotNull String pattern, @NotNull Locale locale) {
return getDefaultFormatter(pattern, locale, null);
}
public static DateTimeFormatter getDefaultFormatter(@NotNull String pattern, @NotNull ZoneId zoneId) {
return getDefaultFormatter(pattern, null, zoneId);
}
public static DateTimeFormatter getDefaultFormatter(@NotNull String pattern) {
return getDefaultFormatter(pattern, DEFAULT_LOCALE);
}
private static String convertByPattern(@NotNull String source, @NotNull String pattern) {
int mmmIndex = pattern.indexOf("MMM");
if (mmmIndex != -1) {
String mmm = source.substring(mmmIndex, mmmIndex + 3);
source = source.replaceAll(mmm, WordUtils.capitalize(mmm.toLowerCase()));
}
return source;
}
public static String format(@NotNull Date date, @NotNull String pattern) {
return new SimpleDateFormat(pattern).format(date);
}
public static String format(@NotNull Date date) {
return format(date, defaultDatePattern);
}
public static String format(@NotNull Temporal temporal, @NotNull String pattern) {
return getDefaultFormatter(pattern).format(temporal);
}
public static String format(@NotNull Temporal temporal) {
String pattern = null;
if (temporal instanceof LocalDate) {
pattern = defaultLocalDatePattern;
} else if (temporal instanceof LocalDateTime) {
pattern = defaultLocalDateTimePattern;
} else if (temporal instanceof LocalTime) {
pattern = defaultLocalTimePattern;
}
return format(temporal, pattern);
}
public static Date parseDate(@NotNull long timeStamp) {
return new Date(timeStamp);
}
public static Date parseDate(@NotNull String source) {
try {
if (source.contains("-") || source.contains(":")) {
String pattern = null;
switch (source.length()) {
case 19:
pattern = PATTERN_UUUU_MM_DD_HH_MM_SS;
break;
case 16:
pattern = PATTERN_UUUU_MM_DD_HH_MM;
break;
case 10:
pattern = PATTERN_UUUU_MM_DD;
break;
case 7:
pattern = PATTERN_UUUU_MM;
break;
case 8:
pattern = PATTERN_HH_MM_SS;
break;
case 5:
pattern = PATTERN_HH_MM;
break;
default:
}
if (pattern != null) {
return new SimpleDateFormat(pattern).parse(source);
}
}
} catch (ParseException e) {
log.error(e.getMessage(), e);
return null;
}
return null;
}
public static LocalDate parseLocalDate(@NotNull long timeStamp, @NotNull ZoneId zoneId) {
return Instant.ofEpochMilli(timeStamp).atZone(zoneId).toLocalDate();
}
public static LocalDate parseLocalDate(@NotNull long timeStamp) {
return parseLocalDate(timeStamp, SYSTEM_ZONE_ID);
}
public static LocalDate parseLocalDate(@NotNull String source, @NotNull String pattern, @NotNull ZoneId zoneId) {
source = convertByPattern(source, pattern);
return LocalDate.parse(source, getDefaultFormatter(pattern, zoneId));
}
public static LocalDate parseLocalDate(@NotNull String source, @NotNull String pattern) {
return parseLocalDate(source, pattern, SYSTEM_ZONE_ID);
}
public static LocalDate parseLocalDate(@NotNull String source, @NotNull ZoneId zoneId, @NotNull String... patterns) {
LocalDate result = null;
for (String pattern : patterns) {
try {
result = parseLocalDate(source, pattern, zoneId);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalDate parseLocalDate(@NotNull String source, @NotNull String... patterns) {
LocalDate result = null;
for (String pattern : patterns) {
try {
result = parseLocalDate(source, pattern);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalDate parseLocalDate(@NotNull String source) {
int length = source.length();
String pattern = null;
if (source.contains("-") || source.contains(":")) {
switch (length) {
case 10:
pattern = PATTERN_UUUU_MM_DD;
break;
case 7:
pattern = PATTERN_UUUU_MM;
break;
}
if (pattern != null) {
return parseLocalDate(source, pattern);
}
}
return null;
}
public static LocalDateTime parseLocalDateTime(@NotNull long timeStamp, @NotNull ZoneId zoneId) {
return Instant.ofEpochMilli(timeStamp).atZone(zoneId).toLocalDateTime();
}
public static LocalDateTime parseLocalDateTime(@NotNull long timeStamp) {
return parseLocalDateTime(timeStamp, SYSTEM_ZONE_ID);
}
public static LocalDateTime parseLocalDateTime(@NotNull String source, @NotNull String pattern, @NotNull ZoneId zoneId) {
if (StringUtils.isBlank(source)) {
return null;
}
source = convertByPattern(source, pattern);
return LocalDateTime.parse(source, getDefaultFormatter(pattern, zoneId));
}
public static LocalDateTime parseLocalDateTime(@NotNull String source, @NotNull String pattern) {
return parseLocalDateTime(source, pattern, SYSTEM_ZONE_ID);
}
public static LocalDateTime parseLocalDateTime(@NotNull String source, @NotNull ZoneId zoneId, @NotNull String... patterns) {
LocalDateTime result = null;
for (String pattern : patterns) {
try {
result = parseLocalDateTime(source, pattern, zoneId);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalDateTime parseLocalDateTime(@NotNull String source, @NotNull String... patterns) {
LocalDateTime result = null;
for (String pattern : patterns) {
try {
result = parseLocalDateTime(source, pattern);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalDateTime parseLocalDateTime(@NotNull String source) {
String pattern = null;
if (source.contains("-") || source.contains(":")) {
switch (source.length()) {
case 19:
pattern = PATTERN_UUUU_MM_DD_HH_MM_SS;
break;
case 16:
pattern = PATTERN_UUUU_MM_DD_HH_MM;
break;
case 10:
pattern = PATTERN_UUUU_MM_DD;
break;
case 7:
pattern = PATTERN_UUUU_MM;
break;
case 8:
pattern = PATTERN_HH_MM_SS;
break;
case 5:
pattern = PATTERN_HH_MM;
break;
default:
}
if (pattern != null) {
return parseLocalDateTime(source, pattern);
}
}
return null;
}
public static LocalTime parseLocalTime(@NotNull long timeStamp, @NotNull ZoneId zoneId) {
return Instant.ofEpochMilli(timeStamp).atZone(zoneId).toLocalTime();
}
public static LocalTime parseLocalTime(@NotNull long timeStamp) {
return parseLocalTime(timeStamp, SYSTEM_ZONE_ID);
}
public static LocalTime parseLocalTime(@NotNull String source, @NotNull String pattern, @NotNull ZoneId zoneId) {
if (StringUtils.isBlank(source)) {
return null;
}
source = convertByPattern(source, pattern);
return LocalTime.parse(source, getDefaultFormatter(pattern, zoneId));
}
public static LocalTime parseLocalTime(@NotNull String source, @NotNull String pattern) {
return parseLocalTime(source, pattern, SYSTEM_ZONE_ID);
}
public static LocalTime parseLocalTime(@NotNull String source, @NotNull ZoneId zoneId, @NotNull String... patterns) {
LocalTime result = null;
for (String pattern : patterns) {
try {
result = parseLocalTime(source, pattern, zoneId);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalTime parseLocalTime(@NotNull String source, @NotNull String... patterns) {
LocalTime result = null;
for (String pattern : patterns) {
try {
result = parseLocalTime(source, pattern);
} catch (Exception ignore) {
}
}
return result;
}
public static LocalTime parseLocalTime(@NotNull String source) {
String pattern = null;
if (source.contains("-") || source.contains(":")) {
switch (source.length()) {
case 8:
pattern = PATTERN_HH_MM_SS;
break;
case 5:
pattern = PATTERN_HH_MM;
break;
default:
}
if (pattern != null) {
return parseLocalTime(source, pattern);
}
}
return null;
}
public static Date toDate(@NotNull Temporal temporal) {
if (temporal instanceof LocalDate) {
return Date.from(((LocalDate) temporal).atStartOfDay().atZone(SYSTEM_ZONE_ID).toInstant());
} else if (temporal instanceof LocalDateTime) {
return Date.from(((LocalDateTime) temporal).atZone(SYSTEM_ZONE_ID).toInstant());
} else if (temporal instanceof LocalTime) {
return Date.from(minLocalDateTime(temporal).atZone(SYSTEM_ZONE_ID).toInstant());
}
return null;
}
public static LocalDate toLocalDate(@NotNull Date date) {
return parseLocalDate(date.getTime());
}
public static LocalDateTime toLocalDateTime(@NotNull Date date) {
return parseLocalDateTime(date.getTime());
}
public static LocalTime toLocalTime(@NotNull Date date) {
return parseLocalTime(date.getTime());
}
public static LocalDateTime minLocalDateTime(@NotNull Temporal temporal) {
if (temporal instanceof LocalDateTime) {
return (LocalDateTime) temporal;
}
LocalDateTime localDateTime = LocalDateTime.now();
if (temporal instanceof LocalDate) {
localDateTime.with(ChronoField.YEAR, ((LocalDate) temporal).getYear());
localDateTime.with(ChronoField.MONTH_OF_YEAR, ((LocalDate) temporal).getMonthValue());
localDateTime.with(ChronoField.DAY_OF_MONTH, ((LocalDate) temporal).getDayOfMonth());
} else {
localDateTime.with(ChronoField.YEAR, 1970);
localDateTime.with(ChronoField.MONTH_OF_YEAR, 1);
localDateTime.with(ChronoField.DAY_OF_MONTH, 1);
}
if (temporal instanceof LocalTime) {
localDateTime.with(ChronoField.HOUR_OF_DAY, ((LocalTime) temporal).getHour());
localDateTime.with(ChronoField.MINUTE_OF_HOUR, ((LocalTime) temporal).getMinute());
localDateTime.with(ChronoField.SECOND_OF_MINUTE, ((LocalTime) temporal).getSecond());
localDateTime.with(ChronoField.MILLI_OF_SECOND, temporal.getLong(ChronoField.MILLI_OF_SECOND));
} else {
localDateTime.with(ChronoField.HOUR_OF_DAY, 0);
localDateTime.with(ChronoField.MINUTE_OF_HOUR, 0);
localDateTime.with(ChronoField.SECOND_OF_MINUTE, 0);
localDateTime.with(ChronoField.MILLI_OF_SECOND, 0);
}
return localDateTime;
}
public static LocalDateTime minLocalDateTime() {
LocalDateTime localDateTime = LocalDateTime.now();
localDateTime.with(ChronoField.YEAR, 1970);
localDateTime.with(ChronoField.MONTH_OF_YEAR, 1);
localDateTime.with(ChronoField.DAY_OF_MONTH, 1);
localDateTime.with(ChronoField.HOUR_OF_DAY, 0);
localDateTime.with(ChronoField.MINUTE_OF_HOUR, 0);
localDateTime.with(ChronoField.SECOND_OF_MINUTE, 0);
localDateTime.with(ChronoField.MILLI_OF_SECOND, 0);
return localDateTime;
}
public static LocalDate withZoneInstant(@NotNull LocalDate localDate, @NotNull ZoneId oldZoneId, @NotNull ZoneId newZoneId) {
return localDate.atStartOfDay().atZone(oldZoneId).withZoneSameInstant(newZoneId).toLocalDate();
}
public static LocalDateTime withZoneInstant(@NotNull LocalDateTime localDateTime, @NotNull ZoneId oldZoneId, @NotNull ZoneId newZoneId) {
return localDateTime.atZone(oldZoneId).withZoneSameInstant(newZoneId).toLocalDateTime();
}
public static LocalTime withZoneInstant(@NotNull LocalTime localTime, @NotNull ZoneId oldZoneId, @NotNull ZoneId newZoneId) {
return minLocalDateTime(localTime).atZone(oldZoneId).withZoneSameInstant(newZoneId).toLocalTime();
}
public static String now() {
return format(new Date());
}
public static String now(@NotNull ZoneId zoneId) {
return format(LocalDateTime.now().atZone(zoneId));
}
public static LocalDateTime todayMinDateTime() {
return LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
}
public static LocalDateTime todayMinDateTime(@NotNull ZoneId zoneId) {
return todayMinDateTime().atZone(zoneId).toLocalDateTime();
}
public static LocalTime todayMinTime() {
return todayMinDateTime().toLocalTime();
}
public static LocalTime todayMinTime(@NotNull ZoneId zoneId) {
return todayMinDateTime(zoneId).toLocalTime();
}
public static String todayMinStr(@NotNull String pattern) {
return format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN), pattern);
}
public static String todayMinStr() {
return format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN), defaultLocalTimePattern);
}
public static LocalDateTime todayMaxDateTime() {
return LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
}
public static LocalDateTime todayMaxDateTime(@NotNull ZoneId zoneId) {
return todayMaxDateTime().atZone(zoneId).toLocalDateTime();
}
public static LocalTime todayMaxTime() {
return todayMaxDateTime().toLocalTime();
}
public static LocalTime todayMaxTime(@NotNull ZoneId zoneId) {
return todayMaxDateTime(zoneId).toLocalTime();
}
public static String todayMaxStr(@NotNull String pattern) {
return format(LocalDateTime.of(LocalDate.now(), LocalTime.MAX), pattern);
}
public static String todayMaxStr() {
return format(LocalDateTime.of(LocalDate.now(), LocalTime.MAX), defaultLocalTimePattern);
}
public static <T extends Temporal> T plusOrMinus(@NotNull T temporal, @NotNull long augendOrMinuend, ChronoUnit chronoUnit) {
if (chronoUnit == null) {
chronoUnit = ChronoUnit.MILLIS;
}
if (augendOrMinuend < 0) {
return (T) temporal.minus(Math.abs(augendOrMinuend), chronoUnit);
} else if (augendOrMinuend > 0) {
return (T) temporal.plus(augendOrMinuend, chronoUnit);
}
return temporal;
}
public static boolean isIntersection(@NotNull LocalDateTime x1, @NotNull LocalDateTime y1, @NotNull LocalDateTime x2, @NotNull LocalDateTime y2) {
return !(y1.isBefore(x2) || y2.isBefore(x1));
}
public static LocalDateTime[] getIntersection(@NotNull LocalDateTime x1, @NotNull LocalDateTime y1, @NotNull LocalDateTime x2, @NotNull LocalDateTime y2) {
if (!isIntersection(x1, y1, x2, y2)) {
return null;
}
LocalDateTime[] result = new LocalDateTime[2];
if (x1.isBefore(x2) || x1.isEqual(x2)) {
result[0] = x2;
} else if (x1.isAfter(x2)) {
result[0] = x1;
}
if (y1.isBefore(y2) || y1.isEqual(y2)) {
result[1] = y1;
} else if (y1.isAfter(y2)) {
result[1] = y2;
}
return result;
}
public static List<LocalDateTime[]> getDifferenceSetsByIntersectional(@NotNull LocalDateTime x1, @NotNull LocalDateTime y1, @NotNull LocalDateTime x2, @NotNull LocalDateTime y2) {
LocalDateTime[] intersections = getIntersection(x1, y1, x2, y2);
if (intersections == null || intersections.length == 0) {
return null;
}
List<LocalDateTime[]> result = new ArrayList<>();
if (x1.isBefore(x2)) {
result.add(new LocalDateTime[]{x1, x2});
} else if (x1.isAfter(x2)) {
result.add(new LocalDateTime[]{x2, x1});
}
if (y1.isBefore(y2)) {
result.add(new LocalDateTime[]{y1, y2});
} else if (y1.isAfter(y2)) {
result.add(new LocalDateTime[]{y2, y1});
}
for (Iterator<LocalDateTime[]> iterator = result.iterator(); iterator.hasNext(); ) {
LocalDateTime[] localDateTimes = iterator.next();
if (localDateTimes[0].equals(intersections[1])) {
localDateTimes[0] = plusOrMinus(localDateTimes[0], 1, ChronoUnit.DAYS);
}
if (localDateTimes[1].equals(intersections[0])) {
localDateTimes[1] = plusOrMinus(localDateTimes[1], -1, ChronoUnit.DAYS);
}
if (localDateTimes[1].isBefore(localDateTimes[0])) {
iterator.remove();
}
}
return result;
}
public static String[] convertWeeks(@NotNull String weeks, @NotNull String splitRegex) {
if (RegExUtils.isMatchedByGroup0("[^,1-7]*", weeks)) {
weeks = weeks.replaceAll("[^,1-7]*", "");
}
if (StringUtils.isBlank(weeks)) {
return new String[]{};
}
return weeks.split(splitRegex);
}
public static String[] convertWeeks(@NotNull String weeks) {
String regex = ",";
if (!weeks.contains(regex)) {
regex = "";
}
return convertWeeks(weeks, regex);
}
public static List<LocalDateTime> getByWeeks(@NotNull String weeks, @NotNull LocalDateTime... times) {
List<LocalDateTime> timeList = null;
if (!CollectionUtils.sizeIsEmpty(times)) {
List<String> weekList = Arrays.asList(convertWeeks(weeks));
timeList = new ArrayList<>(Arrays.asList(times));
timeList.removeIf(time -> !weekList.contains(String.valueOf(time.getDayOfWeek().getValue())));
}
return timeList;
}
public static List<String> getByRange(@NotNull LocalDateTime startTime, @NotNull LocalDateTime endTime, @NotNull String pattern) {
List<String> result = new ArrayList<>();
long distance = ChronoUnit.DAYS.between(startTime, endTime);
if (distance >= 1) {
Stream.iterate(startTime, day -> day.plusDays(1)).limit(distance + 1).forEach(f -> result.add(format(f, pattern)));
}
return result;
}
public static List<String> getByRangeAndWeeks(@NotNull LocalDateTime startTime, @NotNull LocalDateTime endTime, @NotNull String weeks, @NotNull String pattern) {
List<String> result = new ArrayList<>();
TemporalField field = WeekFields.of(DayOfWeek.of(1), 1).dayOfWeek();
LocalDateTime dayByWeek;
for (String week : convertWeeks(weeks)) {
dayByWeek = startTime.with(field, Long.parseLong(week));
if (dayByWeek.isBefore(startTime)) {
dayByWeek = dayByWeek.plusWeeks(1);
}
while (dayByWeek.isBefore(endTime) || dayByWeek.isEqual(endTime)) {
result.add(format(dayByWeek, pattern));
dayByWeek = dayByWeek.plusWeeks(1);
}
}
return result;
}
public static List<LocalDateTime> getByRangeAndWeeks(@NotNull LocalDateTime startTime, @NotNull LocalDateTime endTime, @NotNull String weeks) {
List<LocalDateTime> result = new ArrayList<>();
TemporalField field = WeekFields.of(DayOfWeek.of(1), 1).dayOfWeek();
LocalDateTime tempDay;
for (String week : convertWeeks(weeks)) {
tempDay = startTime.with(field, Long.parseLong(week));
if (tempDay.isBefore(startTime)) {
tempDay = tempDay.plusWeeks(1);
}
while (tempDay.isBefore(endTime) || tempDay.isEqual(endTime)) {
result.add(tempDay);
tempDay = tempDay.plusWeeks(1);
}
}
return result;
}
}
import org.apache.commons.lang3.time.DateFormatUtils;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
public static String YYYY = "yyyy";
public static String YYYY_MM = "yyyy-MM";
public static String YYYY_MM_DD = "yyyy-MM-dd";
public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
public static String YYYYMMDDHHMM = "yyyyMMddHHmm";
public static String YYYY_P_MMDD_P_HHMM = "yyyy.MMdd.HHmm";
public static String YYYYMMDD = "yyyyMMdd";
public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
public static String YEAR_MONTH_DAY_REGEX = "^([1-9]\\d{3}年)(([0]{0,1}[1-9]月)|([1][0-2]月))(([0]{0,1}[1-9]日)|([1-2][0-9]日)|([3][0-2]日))$";
public static String YEAR_MONTH_DAY_REGEX_CUSTOM = "^([1-9]\\d{3}/)(([0]{0,1}[1-9]/)|([1][0-2]/))(([0]{0,1}[1-9])|([1-2][0-9])|([3][0-2]))$";
public static String YYYYMMDDHHMM_REGEX = "^([1-9]\\d{3})(([0]{0,1}[1-9])|([1][0-2]))(([0]{0,1}[1-9])|([1-2][0-9])|([3][0-2]))[0-6][0-9][0-6][0-9]$";
public static SimpleDateFormat sdfOfYYYY_MM_DD = new SimpleDateFormat("yyyy年MM月dd日");
public static SimpleDateFormat sdfOfYYYYMMDD = new SimpleDateFormat(YYYYMMDD);
public static SimpleDateFormat sdfOfYYYYMMDDHHMM = new SimpleDateFormat(YYYYMMDDHHMM);
public static SimpleDateFormat sdfOfYYYY_MM_DD_HH_MM_SS = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS);
public static String scientific = "^((-?\\d+.?\\d*)[Ee]{1}(-?\\d+))$";
public final static String FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
public final static String[] REPLACE_STRING = new String[]{"GMT+0800", "GMT+08:00"};
public final static String SPLIT_STRING = "(中国标准时间)";
private static String[] parsePatterns = {
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy-MM-dd HH",
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy/MM/dd HH",
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM", "yyyy.MM.dd HH",
"yyyyMMddHHmm", "yyyyMMdd"};
public static Date getNowDate() {
return new Date();
}
public static String getYear() {
return dateTimeNow(YYYY);
}
public static String getYearMonth() {
return dateTimeNow(YYYY_MM);
}
public static String getMonth() {
return dateTimeNow("MM");
}
public static String getDate() {
return dateTimeNow(YYYY_MM_DD);
}
public static String getDateYMDHS() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String getTime() {
return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
}
public static final String dateTimeNow() {
return dateTimeNow(YYYYMMDDHHMMSS);
}
public static final String dateTimeNow(final String format) {
return parseDateToStr(format, new Date());
}
public static final String dateTime(final Date date) {
return parseDateToStr(YYYY_MM_DD, date);
}
public static final String parseDateToStr(final String format, final Date date) {
return new SimpleDateFormat(format).format(date);
}
public static String currentTimeMillis() {
return parseDateToStr("yyyy-MM-dd HH:mm:ss:SSS", new Date());
}
public static final Date dateTime(final String format, final String ts) {
try {
return new SimpleDateFormat(format).parse(ts);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
public static final String dateTime() {
Date now = new Date();
return DateFormatUtils.format(now, "yyyyMMdd");
}
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
public static Date getServerStartDate() {
long time = ManagementFactory.getRuntimeMXBean().getStartTime();
return new Date(time);
}
public static Long getDatePoor(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long diff = endDate.getTime() - nowDate.getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
long sec = diff / ns;
return sec;
}
public static Long getStringPoor(String endDate, String nowDate) {
return getDatePoor(parseDate(endDate), parseDate(nowDate));
}
public static Integer getHourPoor(String endDate, String nowDate) {
Long sec = getDatePoor(parseDate(endDate), parseDate(nowDate));
return Integer.valueOf(String.valueOf(sec / 60 / 60));
}
public static Integer getDaysPoor(String endDate, String nowDate) {
Long sec = getDatePoor(parseDate(endDate), parseDate(nowDate));
return Integer.valueOf(String.valueOf(sec / 60 / 60 / 24));
}
public static Date getDateRangeBySeconds(String disposeDate, Integer vsp) {
try {
Date date = parseDate(disposeDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, vsp);
return calendar.getTime();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static Date getDateRangeByMinutes(String disposeDate, Integer vsp) {
try {
Date date = parseDate(disposeDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, vsp);
return calendar.getTime();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String getSevenDateAgo() {
Integer seconds = 7 * 24 * 60 * 60;
String date = parseDateToStr(YYYY_MM_DD, new Date());
return parseDateToStr(YYYY_MM_DD_HH_MM_SS, getDateRangeBySeconds(date, 0 - seconds));
}
public static Long getStringHours(String endDate, String nowDate) {
return getDateHours(parseDate(endDate), parseDate(nowDate));
}
public static Long getDateHours(Date endDate, Date nowDate) {
long nd = 1000 * 24 * 60 * 60;
long nh = 1000 * 60 * 60;
long nm = 1000 * 60;
long ns = 1000;
long diff = endDate.getTime() - nowDate.getTime();
long day = diff / nd;
long hour = diff % nd / nh;
long min = diff % nd % nh / nm;
long sec = diff / ns;
return hour;
}
public static Long getDifferenceSeconds(String date1, String date2) {
long ns = 1000;
long diff = parseDate(date1).getTime() - parseDate(date2).getTime();
diff = Math.abs(diff);
long sec = diff / ns;
return sec;
}
public static long dayDiff(String date1, String date2, String format) {
SimpleDateFormat formater = new SimpleDateFormat(format);
long diff = 0L;
try {
long d1 = formater.parse(date1).getTime();
long d2 = formater.parse(date2).getTime();
diff = (d1 - d2) / (1000 * 60 * 60 * 24);
} catch (ParseException e) {
e.printStackTrace();
}
return diff;
}
public static String getToDay(int num) {
Calendar calendar1 = Calendar.getInstance();
calendar1.add(Calendar.DATE, num);
Date today = calendar1.getTime();
return DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, today);
}
public static String dateForStr(String date) {
try {
SimpleDateFormat inSDF = new SimpleDateFormat("yyyy-MM-dd");
Date inDate = inSDF.parse(date);
date = inSDF.format(inDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String dateToString(String date) {
try {
SimpleDateFormat inSDF = new SimpleDateFormat("yyyyMMddHHmm");
Date inDate = inSDF.parse(date);
date = inSDF.format(inDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
public static String dateToString(Date time) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(time);
}
public static String dateAddOne(String time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
try {
Date dd = df.parse(time);
calendar.setTime(dd);
calendar.add(Calendar.DAY_OF_MONTH, 1);
} catch (ParseException e) {
e.printStackTrace();
}
return df.format(calendar.getTime());
}
public static String dateAddOneNoHms(String time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
try {
Date dd = df.parse(time);
calendar.setTime(dd);
calendar.add(Calendar.DAY_OF_MONTH, 1);
} catch (ParseException e) {
e.printStackTrace();
}
return df.format(calendar.getTime());
}
public static String hourAdd8(String time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
try {
Date dd = df.parse(time);
calendar.setTime(dd);
calendar.add(Calendar.HOUR, 8);
} catch (ParseException e) {
e.printStackTrace();
}
return df.format(calendar.getTime());
}
public static String dateDeleteOne(String time) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date();
try {
long dif = df.parse(time).getTime() - 86400 * 1000;
date.setTime(dif);
} catch (ParseException e) {
e.printStackTrace();
}
return df.format(date);
}
public static String utcToPek(String time) {
try {
Calendar calendar = Calendar.getInstance();
Date dd = parseDate(time);
calendar.setTime(dd);
calendar.add(Calendar.HOUR, 8);
return parseDateToStr(YYYYMMDDHHMM, calendar.getTime());
} catch (Exception e) {
return SysConstants.STRING_VACANCY;
}
}
public static String pekToUtc(String time) {
Calendar calendar = Calendar.getInstance();
Date dd = parseDate(time);
calendar.setTime(dd);
calendar.add(Calendar.HOUR, -8);
return parseDateToStr(YYYYMMDDHHMM, calendar.getTime());
}
public static String addTime(String time, Integer vsp) {
Calendar calendar = Calendar.getInstance();
Date dd = parseDate(time);
calendar.setTime(dd);
calendar.add(Calendar.HOUR, vsp);
return parseDateToStr(YYYYMMDDHHMM, calendar.getTime());
}
public static Date addMinute(Date date, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
public static int betweenAndDate(Date starDate, Date endDate, Date compareDate) {
if (starDate.getTime() <= compareDate.getTime() && compareDate.getTime() <= endDate.getTime()) {
return 1;
} else {
return -1;
}
}
public static String getStartOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
public static String getEndOfDay(Date time) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(time);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
}
public static boolean isOverlap(String startDate1, String endDate1, String startDate2, String endDate2) {
Date leftStartDate = null;
Date leftEndDate = null;
Date rightStartDate = null;
Date rightEndDate = null;
try {
leftStartDate = parseDate(startDate1);
leftEndDate = parseDate(endDate1);
rightStartDate = parseDate(startDate2);
rightEndDate = parseDate(endDate2);
} catch (Exception e) {
return false;
}
return ((leftStartDate.getTime() >= rightStartDate.getTime()) && leftStartDate.getTime() < rightEndDate.getTime())
|| ((leftStartDate.getTime() > rightStartDate.getTime()) && leftStartDate.getTime() <= rightEndDate.getTime())
|| ((rightStartDate.getTime() >= leftStartDate.getTime()) && rightStartDate.getTime() < leftEndDate.getTime())
|| ((rightStartDate.getTime() > leftStartDate.getTime()) && rightStartDate.getTime() <= leftEndDate.getTime());
}
public static List<List<String>> groupConsecutiveDates(List<String> datas) {
datas.sort(String::compareTo);
List<List<String>> result = new ArrayList<>();
List<String> group = null;
for (String value : datas) {
if (group == null || !DateUtils.dateAddOneNoHms(group.get(group.size() - 1)).equals(value)) {
group = new ArrayList<>();
result.add(group);
}
group.add(value);
}
return result;
}
public static List<String> getDatesBetweenTwoDate(Date beginDate, Date endDate) {
List<String> lDate = new ArrayList<>();
lDate.add(parseDateToStr("yyyy-MM-dd", beginDate));
Calendar cal = Calendar.getInstance();
cal.setTime(beginDate);
boolean bContinue = true;
while (bContinue) {
cal.add(Calendar.DAY_OF_MONTH, 1);
if (endDate.after(cal.getTime())) {
lDate.add(parseDateToStr("yyyy-MM-dd", cal.getTime()));
} else {
break;
}
}
lDate.add(parseDateToStr("yyyy-MM-dd", endDate));
return lDate;
}
public static Date longToData(String dataStr) {
Date d = null;
try {
d = sdfOfYYYYMMDDHHMM.parse(dataStr);
} catch (ParseException e) {
e.printStackTrace();
}
return d;
}
public static Date pekToString(String dateString) {
try {
dateString = dateString.split(Pattern.quote(SPLIT_STRING))[0].replace(REPLACE_STRING[0], REPLACE_STRING[1]);
SimpleDateFormat sf1 = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss z", Locale.US);
Date date = sf1.parse(dateString);
return date;
} catch (Exception e) {
throw new RuntimeException("时间转化格式错误" + "[dateString=" + dateString + "]" + "[FORMAT_STRING=" + FORMAT_STRING + "]");
}
}
public static boolean isEffectiveDate(String nowTime, String startTime, String endTime ,String format) {
Date nowDate = dateTime(format,nowTime);
Date startDate = dateTime(format,startTime);
Date stopDate = dateTime(format,endTime);
if (nowDate.getTime() == startDate.getTime()
|| nowDate.getTime() == stopDate.getTime()) {
return true;
}
Calendar date = Calendar.getInstance();
date.setTime(nowDate);
Calendar begin = Calendar.getInstance();
begin.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(stopDate);
if (date.after(begin) && date.before(end)) {
return true;
} else {
return false;
}
}
public static long addtime(long date,int hours){
long result = date;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateStr = sdf.format(new Date((date-116445024000000000L)/10/1000));
LocalDate localDate = LocalDate.parse(dateStr,format);
LocalTime localTime = LocalTime.parse(dateStr,format);
LocalDateTime dateTime = LocalDateTime.of(localDate,localTime);
LocalDateTime addTime = dateTime.plusHours(hours);
LocalDateTime reduceTime = dateTime.minusHours(hours);
result = sdf.parse(addTime.format(format)).getTime()*10*1000 + 116445024000000000L;
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
}