持续更新中
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
/**
* TODO JDK8 日期工具类(不用于线上,因为JDK8太先进,只用于个人总结)
*
* @author liuzebiao
* @Date 2020-4-29 10:13
*/
public class DateUtils {
/**
* 获取当前时间的时间戳(10位:不带毫秒)
*/
public static Long getTimeStamp() {
LocalDateTime now = LocalDateTime.now();
return now.toEpochSecond(OffsetDateTime.now().getOffset());
}
/**
* 获取当前时间的时间戳(13位:带毫秒)
*/
public static Long getTimeStampWithMs() {
LocalDateTime now = LocalDateTime.now();
return now.toInstant(OffsetDateTime.now().getOffset()).toEpochMilli();
}
/**
* Long --> String
*/
public static String long2String(Long time, String pattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return dtf.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(time), ZoneId.systemDefault()));
}
/**
* String --> Long
*/
public static Long string2Long(String time, String pattern) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
LocalDateTime parse = LocalDateTime.parse(time, dtf);
return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}
/**
* 获取本月第一天
*/
public static LocalDate firstDayOfThisMonth() {
LocalDate today = LocalDate.now();
return today.with(TemporalAdjusters.firstDayOfMonth());
}
/**
* 获取本月第N天
*/
public static LocalDate dayOfThisMonth(int n) {
LocalDate today = LocalDate.now();
return today.withDayOfMonth(n);
}
/**
* 获取本月最后一天
*/
public static LocalDate lastDayOfThisMonth() {
LocalDate today = LocalDate.now();
return today.with(TemporalAdjusters.lastDayOfMonth());
}
/**
* 获取指定月的最后一天
* @param month 1-12
*/
public static LocalDate lastDayOfMonth(int year,int month) {
LocalDate ofDate = LocalDate.of(year, month, 1);
return ofDate.with(TemporalAdjusters.lastDayOfMonth());
}
/**
* 获取本月第一天的开始时间
*/
public static String startOfThisMonth(String pattern) {
LocalDateTime ofDateTime = LocalDateTime.of(firstDayOfThisMonth(), LocalTime.MIN);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return ofDateTime.format(dtf);
}
/**
* 取本月最后一天的结束时间
*/
public static String endOfThisMonth(String pattern) {
LocalDateTime ofDateTime = LocalDateTime.of(lastDayOfThisMonth(), LocalTime.MAX);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(pattern);
return ofDateTime.format(dtf);
}
public static void main(String[] args) {
System.out.println(firstDayOfThisMonth());
System.out.println(dayOfThisMonth(7));
System.out.println(lastDayOfThisMonth());
System.out.println(lastDayOfMonth(2020, 2));
System.out.println(startOfThisMonth("yyyy-MM-dd HH:mm:ss"));
System.out.println(endOfThisMonth("yyyy-MM-dd HH:mm:ss"));
}
}