时间工具类
对于老的项目,一般都是用SimpleDateFormat,代码进行扫描的时候,会有线程安全问题。一般有两种解决方案,一是使用第三方时间插件,如Joda-Time,第二是使用jdk8的LocalDate,这里,写了两个工具类提供参考。
Joda-Time
public class JodaTimeUtil {
private static final String FORMAT_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static String getCurrentTime() {
DateTime dt = new DateTime();
String time = dt.toString(FORMAT_TIME_PATTERN);
return time;
}
public static String getCurrentTimePattern(String pattern) {
DateTime dt = new DateTime();
String time = dt.toString(pattern);
return time;
}
public static String getCurrentDate() {
DateTime dt = new DateTime();
String date = dt.toString(FORMAT_TIME_PATTERN);
return date;
}
public static String getCurrentDatePattern(String pattern) {
DateTime dt = new DateTime();
String date = dt.toString(pattern);
return date;
}
public static String getPointTime(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer seconds) {
DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
String date = dt.toString(FORMAT_TIME_PATTERN);
return date;
}
public static String getPointTimePattern(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer seconds, String parrten) {
DateTime dt = new DateTime(year, month, day, hour, minute, seconds);
String date = dt.toString(parrten);
return date;
}
public static String getPointDate(Integer year, Integer month, Integer day) {
LocalDate dt = new LocalDate(year, month, day);
String date = dt.toString(FORMAT_TIME_PATTERN);
return date;
}
public static String getPointDatParrten(Integer year, Integer month, Integer day, String parrten) {
LocalDate dt = new LocalDate(year, month, day);
String date = dt.toString(parrten);
return date;
}
public static String getWeek() {
DateTime dts = new DateTime();
String week = null;
switch (dts.getDayOfWeek()) {
case DateTimeConstants.SUNDAY:
week = "星期日";
break;
case DateTimeConstants.MONDAY:
week = "星期一";
break;
case DateTimeConstants.TUESDAY:
week = "星期二";
break;
case DateTimeConstants.WEDNESDAY:
week = "星期三";
break;
case DateTimeConstants.THURSDAY:
week = "星期四";
break;
case DateTimeConstants.FRIDAY:
week = "星期五";
break;
case DateTimeConstants.SATURDAY:
week = "星期六";
default:
break;
}
return week;
}
public static String getWeekPoint(Integer year, Integer month, Integer day) {
LocalDate dts = new LocalDate(year, month, day);
String week = null;
switch (dts.getDayOfWeek()) {
case DateTimeConstants.SUNDAY:
week = "星期日";
break;
case DateTimeConstants.MONDAY:
week = "星期一";
break;
case DateTimeConstants.TUESDAY:
week = "星期二";
break;
case DateTimeConstants.WEDNESDAY:
week = "星期三";
break;
case DateTimeConstants.THURSDAY:
week = "星期四";
break;
case DateTimeConstants.FRIDAY:
week = "星期五";
break;
case DateTimeConstants.SATURDAY:
week = "星期六";
break;
default:
break;
}
return week;
}
public static String forwardDay(Integer days, String format) {
DateTime dt = new DateTime();
DateTime y = dt.minusDays(days);
return y.toString(format);
}
public static Date forwardDay(Integer days) {
DateTime dt = new DateTime();
DateTime y = dt.minusDays(days);
return y.toDate();
}
public static Date day00(Integer days, String date, String zimeZone) throws Throwable {
DateTime dt;
TimeZone timeZone;
try {
if (StringUtils.isBlank(zimeZone)) {
timeZone = TimeZone.getDefault();
} else {
timeZone = TimeZone.getTimeZone(zimeZone);
}
if (StringUtils.isBlank(date)) {
dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
} else {
dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
}
} catch (Exception e) {
throw new Throwable(e);
}
DateTime y = dt.minusDays(days).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
return y.toDate();
}
public static Date day59(Integer days, String date, String zimeZone) throws Throwable {
DateTime dt;
TimeZone timeZone;
try {
if (StringUtils.isBlank(zimeZone)) {
timeZone = TimeZone.getDefault();
} else {
timeZone = TimeZone.getTimeZone(zimeZone);
}
if (StringUtils.isBlank(date)) {
dt = new DateTime().withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
} else {
dt = new DateTime(date).withZone(DateTimeZone.forTimeZone(timeZone)).toLocalDateTime().toDateTime();
}
} catch (Exception e) {
throw new Throwable(e);
}
DateTime y = dt.minusDays(days).withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
return y.toDate();
}
public static Integer diffDay(Date startDate, Date endDate) {
if (startDate == null || endDate == null) {
return null;
}
DateTime dt1 = new DateTime(startDate);
DateTime dt2 = new DateTime(endDate);
int day = Days.daysBetween(dt1, dt2).getDays();
return Math.abs(day);
}
public static Date lastDay(Date date, Integer month) {
DateTime dt1;
if (month == null) {
month = 0;
}
if (date == null) {
dt1 = new DateTime().minusMonths(month);
} else {
dt1 = new DateTime(date).minusMonths(month);
}
DateTime lastDay = dt1.dayOfMonth().withMaximumValue().
withHourOfDay(23).withMinuteOfHour(59).withSecondOfMinute(59);
return lastDay.toDate();
}
public static Date firstDay(Date date, Integer month) {
DateTime dt1;
if (month == null) {
month = 0;
}
if (date == null) {
dt1 = new DateTime().minusMonths(month);
} else {
dt1 = new DateTime(date).minusMonths(month);
}
DateTime lastDay = dt1.dayOfMonth().withMinimumValue().
withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
return lastDay.toDate();
}
public static Date addDay(Date date, int offset) {
DateTime dt1;
if (date == null) {
dt1 = new DateTime().plusDays(offset);
return dt1.toDate();
}
dt1 = new DateTime(date).plusDays(offset);
return dt1.toDate();
}
public static String getNewUpdateDateString(Date now, Date createDate) {
if (now == null || createDate == null) {
return null;
}
Long time = (now.getTime() - createDate.getTime());
if (time > (24 * 60 * 60 * 1000)) {
return time / (24 * 60 * 60 * 1000) + "天前";
} else if (time > (60 * 60 * 1000)) {
return time / (60 * 60 * 1000) + "小时前";
} else if (time > (60 * 1000)) {
return time / (60 * 1000) + "分钟前";
} else if (time >= 1000) {
return time / 1000 + "秒前";
}
return "刚刚";
}
public static Date stringToDate(String dateTimeStr, String formatStr){
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
return dateTime.toDate();
}
public static void main(String[] args) {
System.out.println(stringToDate("2020-07-02 10:35:32","yyyy-MM-dd HH:mm:ss"));
}
LocalDateUtil
public class LocalDateUtil {
private final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
private final static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
private final static String YYYY_MM_DD = "yyyy-MM-dd";
private final static String YYYYMMDD = "yyyyMMdd";
public static LocalDateTime convertDateToLDT(Date date) {
return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public static Date convertLDTToDate(LocalDateTime time) {
return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
}
public static Long getMilliByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
public static Long getSecondsByTime(LocalDateTime time) {
return time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond();
}
public static String formatTime(LocalDateTime time, String pattern) {
return time.format(DateTimeFormatter.ofPattern(pattern));
}
public static String formatNow(String pattern) {
return formatTime(LocalDateTime.now(), pattern);
}
public static LocalDateTime plus(LocalDateTime time, long number, TemporalUnit field) {
return time.plus(number, field);
}
public static LocalDateTime minu(LocalDateTime time, long number, TemporalUnit field) {
return time.minus(number, field);
}
public static long betweenTwoTime(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit field) {
Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));
if (field == ChronoUnit.YEARS) return period.getYears();
if (field == ChronoUnit.MONTHS) return period.getMonths();
if (field == ChronoUnit.DAYS) return period.getDays();
return field.between(startTime, endTime);
}
public static LocalDateTime getDayStart(LocalDateTime time) {
return time.withHour(0)
.withMinute(0)
.withSecond(0)
.withNano(0);
}
public static LocalDateTime getDayEnd(LocalDateTime time) {
return time.withHour(23)
.withMinute(59)
.withSecond(59)
.withNano(999999999);
}
public static LocalDateTime parseStringToDateTime(String time, String pattern) {
DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
return LocalDateTime.parse(time, df);
}
public static LocalDateTime getNumMonthFirstDay(LocalDateTime time, long number, ChronoUnit field){
LocalDateTime ldt = time.plus(number, field);
return ldt.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime getNumMonthLastDay(LocalDateTime time, long number, ChronoUnit field){
LocalDateTime ldt = time.plus(number, field);
return ldt.with(TemporalAdjusters.lastDayOfMonth());
}
public static boolean isBefore(LocalDateTime before, LocalDateTime after){
return before.isBefore(after);
}
public static boolean isAfter(LocalDateTime before, LocalDateTime after){
return before.isAfter(after);
}
public static boolean isEqual(LocalDateTime before, LocalDateTime after){
return before.isEqual(after);
}
public static boolean isEqualByLocalDate(LocalDateTime before, LocalDateTime after){
return LocalDate.of(before.getYear(),before.getMonthValue(),before.getDayOfMonth()).isEqual(LocalDate.of(after.getYear(),after.getMonthValue(),after.getDayOfMonth()));
}
public static boolean isEqualByMonthDay(LocalDateTime before, LocalDateTime after){
return MonthDay.of(before.getMonthValue(),before.getDayOfMonth()).equals(MonthDay.of(after.getMonthValue(),after.getDayOfMonth()));
}
public static boolean isLeapYear(LocalDateTime time){
return LocalDate.of(time.getYear(),time.getMonthValue(),time.getDayOfMonth()).isLeapYear();
}
public static LocalDateTime getMonthFirsDay(){
LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now(),LocalTime.MIN);
return localDateTime.with(TemporalAdjusters.firstDayOfMonth());
}
public static LocalDateTime getMonthLastDay(){
LocalDateTime localDateTime = LocalDateTime.now();
return localDateTime.with(TemporalAdjusters.lastDayOfMonth());
}
public static LocalDateTime getLastDayMax(){
LocalDateTime lastDateTime = minu(LocalDateTime.now(),1, ChronoUnit.DAYS);
LocalDate localDate = lastDateTime.toLocalDate();
return LocalDateTime.of(localDate,LocalTime.MAX);
}
public static LocalDateTime getNowTimeWeekFirsDay(){
TemporalAdjuster FIRST_OF_WEEK = TemporalAdjusters.ofDateAdjuster(localDate -> localDate.minusDays(localDate
.getDayOfWeek().getValue() - DayOfWeek.MONDAY.getValue()));
return LocalDateTime.of(LocalDate.now(), LocalTime.MIN).with(FIRST_OF_WEEK);
}
public static void main(String[] args) {
System.out.println(convertDateToLDT(new Date()));
System.out.println(formatTime(LocalDateTime.of(2019, 9, 23, 11, 30, 58),YYYY_MM_DD_HH_MM_SS));
System.out.println(formatTime(LocalDateTime.now(),YYYY_MM_DD_HH_MM_SS));
System.out.println(formatNow(YYYY_MM_DD_HH_MM_SS));
System.out.println(formatTime(plus(LocalDateTime.now(),20,ChronoUnit.MINUTES),YYYY_MM_DD_HH_MM_SS));
System.out.println(formatTime(minu(LocalDateTime.now(),2,ChronoUnit.MINUTES),YYYY_MM_DD_HH_MM_SS));
System.out.println("相差多少分:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,9,23,11,40,00),ChronoUnit.MINUTES));
System.out.println("相差多少天:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,9,22,14,40,00),ChronoUnit.DAYS));
System.out.println("相差多少月:" + betweenTwoTime(LocalDateTime.now(),LocalDateTime.of(2019,8,22,14,40,00),ChronoUnit.MONTHS));
System.out.println(formatTime(getDayStart(LocalDateTime.now()),YYYY_MM_DD_HH_MM_SS));
System.out.println(formatTime(getDayEnd(LocalDateTime.now()),YYYY_MM_DD_HH_MM_SS));
System.out.println(parseStringToDateTime("2019-09-23 11:56:59",YYYY_MM_DD_HH_MM_SS));
System.out.println(getNumMonthFirstDay(LocalDateTime.now(),8,ChronoUnit.DAYS));
System.out.println(getNumMonthLastDay(LocalDateTime.now(),8,ChronoUnit.DAYS));
System.out.println(isBefore(LocalDateTime.of(2019,9,23,13,14,00),LocalDateTime.now()));
System.out.println(isAfter(LocalDateTime.of(2019,9,23,13,14,00),LocalDateTime.now()));
System.out.println(isEqual(LocalDateTime.of(2019,9,23,13,17),LocalDateTime.now()));
System.out.println(isEqualByLocalDate(LocalDateTime.of(2019,9,23,16,30),LocalDateTime.of(2019,9,23,13,30)));
System.out.println(isLeapYear(LocalDateTime.of(2019,9,23,13,17)));
System.out.println(isEqualByMonthDay(LocalDateTime.of(2019,9,23,16,30),LocalDateTime.of(2021,9,23,13,30)));
}