Java8时间类API汇总(持续更新) 返回首页

发表于 2020-02-26 | 本文共 120 字

LocalDate/LocalDateTime <==> String

2020-02-26

//LocalDate --> String
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate time = LocalDate.now();
String str = df.format(time);
//String --> LocalDate
LocalDate ldt = LocalDate.parse("2020-02-26", df);

//LocalDateTime --> String
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime time = LocalDateTime.now();
String str = df.format(time);
//String --> LocalDateTime
LocalDateTime ldt = LocalDateTime.parse("2020-02-26 14:42:00", df);

获取某周/月的某一天

2020-02-27

//获取某周的某一天,offset:偏移量
public static LocalDate dayOfWeek(LocalDate date, int offset) {
	LocalDate localDate = date.plusWeeks(offset);
	return localDate.with(DayOfWeek.MONDAY);
}

//获取某月的某一天,offset:偏移量
public static LocalDate dayOfMonth(LocalDate date, int offset) {
	LocalDate localDate = date.plusMonths(offset).with(TemporalAdjusters.firstDayOfMonth());
	return localDate.with(DayOfWeek.MONDAY);
}

获取某天的开始和结束时间(时分秒)

//获取某天的开始时间
public static LocalDateTime getStartOfDay(LocalDate date) {
	return date.atTime(LocalTime.MIN);
}
//获取某天的结束时间
public static LocalDateTime getEndOfDay(LocalDate date) {
	return date.atTime(LocalTime.MAX);
}


如果你觉得本文对你有帮助,不妨请我喝杯咖啡