JAVA日付処理ツール類-DateUtil
9814 ワード
以下は特に説明していないが、いずれもjdk 1.8のバージョンを指す。マルチスレッドの下でSimpleDateFormat(非スレッドセキュリティクラス)を使用すると、次のような問題が発生します。 マルチスレッド環境では、dateStrをDate形式に変換します。 マルチスレッド環境において、dateTimeStrをDate形式に変換する。 オブジェクトはJSON文字列に変換されます。プログレッシブフォーマットは自分で指定します。(例えば、空list、空string、null数字、nullブール値、null Map)。 ステップサイズに従って前または後ろにある日の日付文字列を取得します。 ステップサイズに従って前または後ろにある日の日付文字列を取得します。 指定された参照日(baseDate)とステップサイズに基づいて前または後ろにある日の日付文字列を取得します。 文字列回転Longタイプ。 指定されたフォーマットの文字列に従って、Dateタイプにフォーマットされています。prvate static final String DATE_FOREMAT=「 .ある年がうるう年かどうか判断する。 ステップ長によってN年前またはN年後の年数を返します。 ステップ長によってN年前またはN年後の年数を返します。 JDK 8以前のバージョン:現在の時間の整数時間を取得します。 JDK 8において、現在時刻の正時を取得します。 以下の列挙の種類を通じて*①:LOCAL_DATE .2つの日付間隔のすべての日付を取得します。 MyDateUtils.javaコードリスト:
:
java.lang.NumberFormatException: multiple points
」prvate static final String DATETIME_FOREMAT=「yyyy-MM-dd
」yyyy-MM-dd HH:mm:ss
:フォーマットは「yyy-M-dd」*②:LOCAL_DATETIME
フォーマットは「yyy-M-dd HH:00」です。import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import lombok.extern.slf4j.Slf4j;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;
/**
* User: DavidTest
* Date:
* Time:
* Desc: Java
*/
@Slf4j
public class MyDateUtils {
private static DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static DateTimeFormatter DTF_OF_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final String DATE_FORMAT = "yyyy-MM-dd";
private static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
// ( Date | Datetime )
private static final ThreadLocal THREAD_LOCAL_SDF = new ThreadLocal<>();
// :①:LOCAL_DATE, "yyyy-MM-dd" ;②:LOCAL_DATETIME, : "yyyy-MM-dd HH:mm:ss".
public enum MY_DATE_TYPE {
LOCAL_DATE, LOCAL_DATETIME
}
/**
* , dateStr Date .
* SimpleDateFormat,
* : java.lang.NumberFormatException: multiple points .
*
* @param dateStr
* @return
*/
public static Date parseBySDF(String dateStr) throws ParseException {
SimpleDateFormat sdf = THREAD_LOCAL_SDF.get();
if (sdf == null) {
sdf = new SimpleDateFormat(DATE_FORMAT);
}
log.info(">>>> : " + Thread.currentThread().getName());
Date date = sdf.parse(dateStr);
return date;
}
/**
* , dateTimeStr Date .
* SimpleDateFormat,
* : java.lang.NumberFormatException: multiple points .
*
* @param dateTimeStr
* @return
*/
public static Date parseBySDFLong(String dateTimeStr) throws ParseException {
SimpleDateFormat sdfLong = THREAD_LOCAL_SDF.get();
if (sdfLong == null) {
sdfLong = new SimpleDateFormat(DATETIME_FORMAT);
}
log.info(">>>> : " + Thread.currentThread().getName());
Date date = sdfLong.parse(dateTimeStr);
return date;
}
public static String toJSONStr(Object obj) {
String msg = JSON.toJSONString(obj,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullBooleanAsFalse,
SerializerFeature.WriteMapNullValue);
return msg;
}
public static String getDate(Long daysToAdd) {
LocalDate daysBefore = LocalDate.now().plusDays(daysToAdd);
return daysBefore.format(DTF);
}
public static String getDateTime(Long daysToAdd) {
LocalDateTime daysBefore = LocalDateTime.now().plusDays(daysToAdd);
return daysBefore.format(DTF_OF_TIME);
}
public static String getDate(String baseDate, Long daysToAdd) {
LocalDate daysBefore = LocalDate.parse(baseDate).plusDays(daysToAdd);
return daysBefore.format(DTF);
}
public static Long getLong(String x) {
Long r = null;
try {
r = new Long(x.trim());
} catch (NumberFormatException e) {
log.error("", e);
}
return r;
}
public static Date getDate(String dateStr) {
try {
return new SimpleDateFormat(DATE_FORMAT).parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static String getDateStr(Date date) {
return new SimpleDateFormat(DATETIME_FORMAT).format(date);
}
/**
*
*
* @param year
* @return
*/
public static Boolean isLeapYear(Integer year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return true;
} else {
return false;
}
}
/**
* N N
*
* @param step
* @return
*/
public static Integer getSpecificYearByStep(Integer step) {
LocalDate localDate = LocalDate.now();
return localDate.plusYears(step).getYear();
}
/**
* N N
*
* @param baseDateTime , "2020-04-20 00:00:00"
* @param step , ( step=1, "2020-04-20 01:00:00
* @return
*/
public static String getSpecificDateHourByStep(String baseDateTime, Integer step) {
if (baseDateTime != null && 19 == baseDateTime.length()) {
LocalDateTime localDate = LocalDateTime.parse(baseDateTime, DTF_OF_TIME);
return localDate.plusHours(step).format(DTF_OF_TIME);
} else {
throw new RuntimeException("Parameter baseDateTime's formatter invalid, please check!");
}
}
/**
* 2 .
* :
* 1: localDate1 > localDate2, .
* 2: localDate1 < localDate2, .
*
* @param localDate1
* @param localDate2
* @return
*/
public static Integer getPeriodDays(LocalDate localDate1, LocalDate localDate2) {
return (int) (localDate1.toEpochDay() - localDate2.toEpochDay());
}
/**
* JDK8 :
*
* @return
*/
public static Date getCurrentHourTimeBeforeJDK8() {
Calendar ca = Calendar.getInstance();
ca.set(Calendar.MINUTE, 0);
ca.set(Calendar.SECOND, 0);
ca.set(Calendar.MILLISECOND, 0);
return ca.getTime();
}
/**
* JDK8 :
*
* .
* @return
*/
public static Date getCurrentHourTimeOfJDK8() {
LocalDateTime time = LocalDateTime.now();
return Date.from(time.minusMinutes(time.getMinute()).minusSeconds(time.getSecond()).atZone(ZoneId.systemDefault()).toInstant());
//return Date.from(time.withMinute(0).withSecond(0).atZone(ZoneId.systemDefault()).toInstant());
}
/**
*
* ①: LOCAL_DATE : "yyyy-MM-dd"
* ②: LOCAL_DATETIME : "yyyy-MM-dd HH:00:00"
*
* @return
*/
public static String getCurrentDateOrTimeByType(MY_DATE_TYPE date_type) {
LocalDateTime time = LocalDateTime.now();
switch (date_type) {
case LOCAL_DATE:
return (time.withMinute(0).withSecond(0).withNano(0)).format(DTF);
case LOCAL_DATETIME:
return (time.withMinute(0).withSecond(0).withNano(0)).format(DTF_OF_TIME);
default:
return null;
}
}
/**
*
*
* @param start '2019-01-01'
* @param end '2019-02-01'
* @return
*/
public static List getBetweenDate(String start, String end) {
List list = new ArrayList<>();
LocalDate startDate = LocalDate.parse(start);
LocalDate endDate = LocalDate.parse(end);
long distance = ChronoUnit.DAYS.between(startDate, endDate);
System.out.println("distance = " + distance);
Stream.iterate(startDate, localDate -> localDate.plusDays(1))
.limit(distance + 1)
.forEach(f -> {
list.add(f.toString());
});
return list;
}
public static void main(String[] args) {
// System.out.println(getSpecificYearByStep(-1));
// System.out.println(MyDateUtils.getSpecificYearByStep(0));
// System.out.println(MyDateUtils.getDate("2020-02-29", -366L));
// System.out.println(MyDateUtils.getDate("2019-01-01", 0L));
// System.out.println(MyDateUtils.getDate("2020-02-28", -365L));
// System.out.println(MyDateUtils.getDateTime(0L));
// System.out.println(getCurrentDateOrTimeByType(MY_DATE_TYPE.LOCAL_DATE));
// System.out.println(getCurrentDateOrTimeByType(MY_DATE_TYPE.LOCAL_DATETIME));
// System.out.println((int)((double)297/54*2));
System.out.println(getBetweenDate("2019-05-01", "2020-05-20").size());
System.out.println(getSpecificDateHourByStep("2020-05-21 00:00:00", -1));
}
}