1.LocalDate 表示日期(年月日)
2.LocalTime 表示时间(时分秒)
3.LocalDateTime 表示日期+时间 (年月日时分秒)
1.获取时间对象
public class JDK8DateTest {
public static void main(String[] args) {
//获取当前时间
LocalDateTime now = LocalDateTime.now();
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
System.out.println(now);
System.out.println(of);
}
}
输出:
2022-04-12T21:49:22.301
2022-04-12T21:45:50
2.获取时间中的具体值
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
//获取年份
int year = of.getYear();
//获取月份
int monthValue = of.getMonthValue();
//获取几号
int dayOfMonth = of.getDayOfMonth();
//获取一年中第几天
int dayOfYear = of.getDayOfYear();
//获取星期几
DayOfWeek dayOfWeek = of.getDayOfWeek();
//时
int hour = of.getHour();
//分
int minute = of.getMinute();
//秒
int second = of.getSecond();
}
}
3.日期格式之间的转换
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
//转换为日月年
LocalDate localDate = of.toLocalDate();
//转换为时分秒
LocalTime localTime = of.toLocalTime();
}
}
4.日期与字符串之间的转换
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
//定义字符串格式
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss");
//格式化时间为字符串
String format = of.format(dateTimeFormatter);
//定义时间戳格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss");
//格式化字符串为时间戳
LocalDateTime parse = LocalDateTime.parse(format, formatter);
}
}
5.时间增减
plus和minus系列方法,示例:
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
//时间年份+1 或者-1
LocalDateTime localDateTime = of.plusYears(1);
LocalDateTime localDateTime1 = of.plusYears(-1);
//时间年份-1 或者+1
LocalDateTime localDateTime2 = of.minusYears(1);
LocalDateTime localDateTime3 = of.minusYears(-1);
}
}
6.直接修改年月日时分秒
with系列方法 ,示例:
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDateTime of = LocalDateTime.of(2022, 4, 12, 21, 45, 50);
//直接分别修改年月日
LocalDateTime localDateTime = of.withYear(2021);
LocalDateTime localDateTime1 = of.withMonth(5);
LocalDateTime localDateTime2 = of.withDayOfMonth(24);
}
}
7.计算两时刻直接的差值
public class JDK8DateTest {
public static void main(String[] args) {
//获取具体时间
LocalDate of1 = LocalDate.of(2022, 4, 4);
LocalDate of2 = LocalDate.of(2025, 12, 12);
//计算两个时间的间隔(*LocalDate类型参数)
Period between = Period.between(of1,of2);
//获取时间段的年数
int years = between.getYears();
//获取时间段的月数
int months = between.getMonths();
//获取时间段的天数
int days = between.getDays();
//获取时间段内总共的月数
long l = between.toTotalMonths();
System.out.println(l);//44
}
}