时间日期工具类
- 获取某个日期的最后一天
- 输入的日期和当前日期作比较 0-表示时间日期相同 1-表示当前日期>大于输入日期 -1-表示当前日期<输入日期
- 获取当前时间 格式是:yyyy-MM-dd
- 转换Excel日期为指定格式日期字符串
- 等等
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class DateUtils {
private static String EMPTY = "";
private static String datePattern = "yyyy-MM-dd";
private static String datePattern2 = "yyyy/MM/dd";
private static String datePattern1 = "yyyy-MM";
private static String dateTimePattern = "yyyy-MM-dd HH:mm:ss";
public static String datePatternYMD = "yyyyMMdd";
public static String datePatternY_M_D = "yyyy-MM-dd";
public static String patternYMD = "yyyy-MM-dd";
private static SimpleDateFormat dateFormat = new SimpleDateFormat(datePattern);
private static SimpleDateFormat dateFormat1 = new SimpleDateFormat(datePattern1);
private static SimpleDateFormat dateFormat2 = new SimpleDateFormat(datePattern2);
private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(dateTimePattern);
private static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
private static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateTimePattern);
public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_FORMAT_YYYY_MM_CN = "YYYY年MM月";
private final static ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");
public final static String FORMAT_TIME_FOR_ROW_KEY = "yyyyMMddHHmmss";
public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS2 = "yyyy/MM/dd HH:mm:ss";
public static final String DATE_FORMAT_YYYY_MM_DD2 = "yyyy/MM/dd";
private static final ThreadLocal<SimpleDateFormat> DEFAULT_DATE_FORMAT = ThreadLocal.withInitial(() -> new
SimpleDateFormat(dateTimePattern));
private static final ThreadLocal<SimpleDateFormat> DEFAULT_YTD_DATE_FORMAT = ThreadLocal.withInitial(() -> new
SimpleDateFormat(datePattern));
public static final ThreadLocal<SimpleDateFormat> dateFormatBrief = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
return new SimpleDateFormat(FORMAT_TIME_FOR_ROW_KEY);
}
};
public static Date stringToDateTime(String strDate) {
if (strDate == null) {
return null;
}
ParsePosition pos = new ParsePosition(0);
return dateTimeFormat.parse(strDate, pos);
}
public static Date stringToDate(String strDate) {
if (strDate == null) {
return null;
}
ParsePosition pos = new ParsePosition(0);
return dateFormat.parse(strDate, pos);
}
public static String dateTimeToString(Date dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateTimeFormat.format(dateDate);
}
public static String dateToStringFormat(Date dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateFormat2.format(dateDate);
}
public static String dateYearMonth(Date dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateFormat1.format(dateDate);
}
public static Date parseStrToDate(String time, String timeFromat) {
if (time == null || time.equals("")) {
return null;
}
Date date = null;
try {
DateFormat dateFormat = new SimpleDateFormat(timeFromat);
date = dateFormat.parse(time);
} catch (Exception e) {
}
return date;
}
public static String StringToDateYearMonth(String stringDate) {
SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYYY_MM_CN);
Calendar cal = Calendar.getInstance();
cal.setTime(DateUtils.parseStrToDate(stringDate, datePattern1));
return sdf.format(cal.getTime());
}
public static String dateToString(LocalDate dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateFormatter.format(dateDate);
}
public static String dateToString(Date dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateFormat.format(dateDate);
}
public static String dateTimeToString(LocalDateTime dateDate) {
if (dateDate == null) {
return EMPTY;
}
return dateTimeFormatter.format(dateDate);
}
public static LocalDate dateToLocalDate(Date date) {
if (date == null) {
return null;
}
Instant instant = date.toInstant();
ZoneId zone = ZoneId.systemDefault();
return LocalDateTime.ofInstant(instant, zone).toLocalDate();
}
public static long getDays(LocalDate before) {
if (before == null) {
return 0;
}
LocalDate now = LocalDate.now();
return now.toEpochDay() - before.toEpochDay();
}
public static long getWeeks(LocalDate before) {
if (before == null) {
return 0;
}
long days = getDays(before);
return days / 7;
}
public static long getWeeks(Date before) {
if (before == null) {
return 0;
}
LocalDate localDate = dateToLocalDate(before);
long days = getDays(localDate);
return days / 7;
}
public static Date getMonthFirstDay(Integer month) {
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.MONTH, month);
cal_1.set(Calendar.DAY_OF_MONTH, 1);
cal_1.set(Calendar.HOUR_OF_DAY, 0);
cal_1.set(Calendar.MINUTE, 0);
cal_1.set(Calendar.SECOND, 0);
cal_1.set(Calendar.MILLISECOND, 0);
return cal_1.getTime();
}
public static Date getMonthFirstDayNiHour(Integer month) {
Calendar cal_1 = Calendar.getInstance();
cal_1.add(Calendar.MONTH, month);
cal_1.set(Calendar.DAY_OF_MONTH, 1);
cal_1.set(Calendar.HOUR_OF_DAY, 9);
cal_1.set(Calendar.MINUTE, 0);
cal_1.set(Calendar.SECOND, 0);
cal_1.set(Calendar.MILLISECOND, 0);
return cal_1.getTime();
}
public static Date getLastDayOfMonth(int month) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, month);
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, lastDay);
return cal.getTime();
}
public static long getMonths(Date before) {
dateToString(before);
int i = calDiffMonth(dateToString(before), dateToString(new Date()));
return i;
}
public static int getDay(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.DATE);
}
public static int getMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.MONTH) + 1;
}
public static int getYear(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.get(Calendar.YEAR);
}
public static int getDaysOfMonth(int year, int month) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, 1);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
public static int calDiffMonth(String startDate, String endDate) {
int result = 0;
try {
SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd");
Date start = sfd.parse(startDate);
Date end = sfd.parse(endDate);
int startYear = getYear(start);
int startMonth = getMonth(start);
int startDay = getDay(start);
int endYear = getYear(end);
int endMonth = getMonth(end);
int endDay = getDay(end);
if (startDay > endDay) {
if (endDay == getDaysOfMonth(getYear(new Date()), 2)) {
result = (endYear - startYear) * 12 + endMonth - startMonth;
} else {
result = (endYear - startYear) * 12 + endMonth - startMonth - 1;
}
} else {
result = (endYear - startYear) * 12 + endMonth - startMonth;
}
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
public static List<Integer> yearsInTwoDate(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int startYear = start.get(Calendar.YEAR);
int endYear = end.get(Calendar.YEAR);
List<Integer> years = new ArrayList<>();
for (int i = startYear; i <= endYear; i++) {
years.add(i);
}
return years;
}
public static Map<Integer, Integer> monthDurationPerYear(Date startDate, Date endDate) {
Calendar start = Calendar.getInstance();
start.setTime(startDate);
Calendar end = Calendar.getInstance();
end.setTime(endDate);
int startYear = start.get(Calendar.YEAR);
int endYear = end.get(Calendar.YEAR);
Map<Integer, Integer> duration = new LinkedHashMap<>();
if (startYear == endYear) {
duration.put(startYear, end.get(Calendar.MONTH) - start.get(Calendar.MONTH) + 1);
return duration;
}
duration.put(startYear, 12 - start.get(Calendar.MONTH));
for (int i = startYear + 1; i < endYear; i++) {
duration.put(i, 12);
}
duration.put(endYear, end.get(Calendar.MONTH) + 1);
return duration;
}
public static Integer monthDuration(Date startDate, Date endDate) {
Map<Integer, Integer> monthDurationPerYear = DateUtils.monthDurationPerYear(startDate, endDate);
return monthDurationPerYear.entrySet().stream().map(Map.Entry::getValue)
.collect(Collectors.summingInt(Integer::intValue));
}
public static int longOfTwoDate(Date first, Date second) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(first);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(second);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) {
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
timeDistance += 366;
} else
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else
{
System.out.println("判断day2 - day1 : " + (day2 - day1));
return day2 - day1;
}
}
public static int longOfTwoDate(String start, String end) {
Date first = DateUtils.stringToDate(start);
Date second = DateUtils.stringToDate(end);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(first);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(second);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) {
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
timeDistance += 366;
} else
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else
{
System.out.println("判断day2 - day1 : " + (day2 - day1));
return day2 - day1;
}
}
public static Date getLastMonthLastDay(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.MONTH, -1);
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
Date lastDateOfPrevMonth = c.getTime();
return lastDateOfPrevMonth;
}
public static String getLastDay(String dateStr) {
Date date = DateUtils.stringToDate(dateStr);
int year = DateUtils.getYear(date);
int month = DateUtils.getMonth(date);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date lastDate = cal.getTime();
return DateUtils.dateToString(lastDate);
}
public static String getTheDayBefore(String dateStr) {
Calendar c = Calendar.getInstance();
Date date = DateUtils.stringToDate(dateStr);
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);
return dateToString(c.getTime());
}
public static Date getSpecifiedDayBefore(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);
return c.getTime();
}
public static Date getSpecifiedDayStrBefore(String dateStr) {
Calendar c = Calendar.getInstance();
Date date = DateUtils.stringToDate(dateStr);
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day - 1);
return c.getTime();
}
public static Date getSpecifiedDayNext(String dateStr) {
Date date = DateUtils.stringToDate(dateStr);
Calendar c = Calendar.getInstance();
c.setTime(date);
int day = c.get(Calendar.DATE);
c.set(Calendar.DATE, day + 1);
return c.getTime();
}
public static int compareCurrentDate(String inputTime) {
String currentTime = getCurrentTime();
DateFormat df = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYYY_MM_DD);
try {
Date inputDate = df.parse(inputTime);
Date currentDate = df.parse(currentTime);
return currentDate.compareTo(inputDate);
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static String getCurrentTime() {
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYYY_MM_DD);
String currentStr = sdf.format(dt);
return currentStr;
}
public static int compareCurrentDateTime(String inputTime) {
String currentTime = getCurrentDateTime();
DateFormat df = new SimpleDateFormat(DateUtils.FORMAT_TIME_FOR_ROW_KEY);
try {
Date inputDate = df.parse(inputTime);
Date currentDate = df.parse(currentTime);
return currentDate.compareTo(inputDate);
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static String getCurrentDateTime() {
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.FORMAT_TIME_FOR_ROW_KEY);
String currentStr = sdf.format(dt);
return currentStr;
}
public static String getNowStrTime(){
Date dt = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.datePatternYMD);
String nowStr = sdf.format(dt);
return nowStr;
}
public static Date getcalculateDate(int num){
SimpleDateFormat sf = new SimpleDateFormat(DateUtils.datePatternYMD);
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, num);
return c.getTime();
}
public static int compare(String time1, String time2) {
SimpleDateFormat sdf = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYYY_MM_DD);
try {
Date time1Date = sdf.parse(time1);
Date time2Date = sdf.parse(time2);
return time1Date.compareTo(time2Date);
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
public static String getInputTimeNextDay(String time) {
DateFormat dft = new SimpleDateFormat(DateUtils.DATE_FORMAT_YYYY_MM_DD);
String nextDay = "";
try {
Date temp = dft.parse(time);
Calendar cld = Calendar.getInstance();
cld.setTime(temp);
cld.add(Calendar.DATE, 1);
temp = cld.getTime();
nextDay = dft.format(temp);
} catch (ParseException e) {
e.printStackTrace();
}
return nextDay;
}
public static List<String> getMonthBetween(String minDate, String maxDate) {
ArrayList<String> result = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Calendar min = Calendar.getInstance();
Calendar max = Calendar.getInstance();
try {
min.setTime(sdf.parse(minDate));
min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
max.setTime(sdf.parse(maxDate));
max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar curr = min;
while (curr.before(max)) {
result.add(sdf.format(curr.getTime()));
curr.add(Calendar.MONTH, 1);
}
min = null;
max = null;
curr = null;
return result;
}
public static Date toYMDDate(String dateStr) throws ParseException {
return DEFAULT_YTD_DATE_FORMAT.get().parse(dateStr);
}
public static String toStartDate(String dateStr) throws ParseException {
Date dateTime = DateUtils.toYMDDate(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return DEFAULT_DATE_FORMAT.get().format(calendar.getTime());
}
public static String toEndDate(String dateStr) throws ParseException {
Date dateTime = DateUtils.toYMDDate(dateStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
return DEFAULT_DATE_FORMAT.get().format(calendar.getTime());
}
public static String getBeforeDayZeroTime(int n) {
Calendar calendar = Calendar.getInstance(Locale.CHINA);
calendar.add(Calendar.DAY_OF_YEAR, n);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return DEFAULT_DATE_FORMAT.get().format(calendar.getTime());
}
public static String getBeforeDaySixTime(int n) {
Calendar calendar = Calendar.getInstance(Locale.CHINA);
calendar.add(Calendar.DAY_OF_YEAR, n);
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
return DEFAULT_DATE_FORMAT.get().format(calendar.getTime());
}
public static Integer diffDays(Date start, Date end) {
LocalDate startDate = LocalDateTime.ofInstant(start.toInstant(), ZONE_ID).toLocalDate();
LocalDate endDate = LocalDateTime.ofInstant(end.toInstant(), ZONE_ID).toLocalDate();
if (Objects.isNull(startDate) || Objects.isNull(endDate)) {
return null;
}
Long diffDay = endDate.toEpochDay() - startDate.toEpochDay();
return Math.abs(diffDay.intValue());
}
public static boolean isBetween(Date date, Date startDate, Date endDate) {
return org.apache.commons.lang3.time.DateUtils.truncatedCompareTo(date, startDate, Calendar.DATE) >= 0 && org.apache.commons.lang3.time.DateUtils.truncatedCompareTo(date, endDate, Calendar.DATE) <= 0;
}
public static boolean isValiDate(String strDate,String dateFormat) {
SimpleDateFormat format = new SimpleDateFormat(dateFormat);
try {
format.setLenient(false);
format.parse(strDate);
} catch (Exception e) {
return false;
}
return true;
}
public static void main(String[] args) throws ParseException {
System.out.println(DateUtils.getBeforeDaySixTime(-90));
System.out.println(DateUtils.getBeforeDaySixTime(0));
BigDecimal num1 = new BigDecimal("13.88");
BigDecimal num2 = new BigDecimal("0.6678");
BigDecimal num3 = new BigDecimal("-1000000");
System.out.println(num2.compareTo(BigDecimal.ZERO));
}
public static String conversionDoubleToDateStr(double value,String format){
boolean use1904windowing = false;
int wholeDays = (int)Math.floor(value);
int millisecondsInDay = (int)((value - (double)wholeDays) * 8.64E7D + 0.5D);
Calendar calendar = new GregorianCalendar();
short startYear = 1900;
byte dayAdjust = -1;
if (use1904windowing) {
startYear = 1904;
dayAdjust = 1;
}else if (wholeDays < 61) {
dayAdjust = 0;
}
calendar.set(startYear, 0, wholeDays + dayAdjust, 0, 0, 0);
calendar.set(Calendar.MILLISECOND, millisecondsInDay);
if(calendar.get(Calendar.MILLISECOND) == 0) {
calendar.clear(Calendar.MILLISECOND);
}
Date date = calendar.getTime();
SimpleDateFormat s = new SimpleDateFormat(format);
System.out.println(s.format(date));
return s.format(date);
}
public static int daysBetween(Date smdate,Date bdate) throws ParseException
{
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
smdate=sdf.parse(sdf.format(smdate));
bdate=sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days=(time2-time1)/(1000*3600*24);
return Integer.parseInt(String.valueOf(between_days));
}
private static String DATE_REGEX = "^([1-9]\\d{3}-)(([0]{0,1}[1-9]-)|([1][0-2]-))(([0-3]{0,1}[0-9]))$";
public static boolean validDateEffecitive(String datestr){
boolean matches = false;
try {
matches = Pattern.matches(DATE_REGEX, datestr);
if(!matches){
return matches;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);
sdf.parse(datestr);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return matches;
}
public static Date formatExcelDate(int day) {
Calendar calendar = new GregorianCalendar(1900,0,-1);
Date gregorianDate = calendar.getTime();
return org.apache.commons.lang.time.DateUtils.addDays(gregorianDate, day);
}
public static String formatCurrentDate(String format) {
return formatDate(Calendar.getInstance().getTime(), format);
}
public static String formatDate(Date date, String format) {
SimpleDateFormat dateFormat = new SimpleDateFormat(format);
return dateFormat.format(date);
}
public static Date endTimeDate(Date date){
if (date != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String start = sdf.format(date);
try {
date = sdf1.parse(start + " 23:59:59");
} catch (Exception ignored) {
}
}
return date;
}
}