LocalDateTime的获取方法
public int getYear()
获取年
public int getMonthValue()
获取月
public int getDayOfMonth()
获取月中的天
public int getDayOfYear()
获取年中的天
public DayOfWeek getDayOfWeek()
获取星期中的第几天
public int getHour()
获取小时
public int getMinute()
获取分钟
public int getSecond()
获取秒
LocalDateTime的转换方法
**三者的区别
LocalDateTime: 包含年、月、日、时、分、秒
LocalDate: 包含年、月、日
LocalTime: 包含时、分、秒
**可以通过LocalDateTime转换为LocalDate和LocalTime
public LocalDate toLocalDate()
把LocalDateTime转换为LocalDate
public LocalTime toLocalTime()
把LocalDateTime转换为LocalTime
LocalDateTime的格式化和解析
public String format(DateTimeFormatter formatter(参数为格式,如:yyyy-MM-dd HH:mm:ss))
格式化:把LocalDateTime转换为String
public static LocalDateTime parse(CharSequence text, DateTimeFormatter formatter)
解析:把字符串转换为LocalDateTime对象
**日期格式化代码演示
//获取当前时间的LocalDateTime对象
LocalDateTime localDateTime = LocalDateTime.now();
//创建日期格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//格式化
String str=localDateTime.format(formatter);
System.out.println(str);
**日期解析的代码演示
//创建日期格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//日期解析
LocalDateTime localDateTime= LocalDateTime.parse("2020-08-23 15:19:39",formatter);
//...后面就可以使用LocalDateTime的方法,对时间进行操作
LocalDateTime加减运算方法
public LocalDateTime plusYears(int n)
加、减年
public LocalDateTime plusMonths(int n)
加、减月
public LocalDateTime plusDays(int n)
加、减日
public LocalDateTime plusHours(int n)
加、减时
public LocalDateTime plusMinutes(int n)
加、减分
public LocalDateTime plusSeconds(int n)
加、减秒
LocalDateTime设置时间的方法
public LocalDateTime withYear(int n)
设置年
public LocalDateTime withMonth(int n)
设置月
public LocalDateTime withDay(int n)
设置日
public LocalDateTime withHour(int n)
设置时
public LocalDateTime withMinute(int n)
设置分
public LocalDateTime withSecond(int n)
设置秒
时间间隔类
Period类
**计算两个时间间隔的年、月、日。
//生日的时间
LocalDate localDate1 = LocalDate.of(1996, 6, 23);
//今天的时间
LocalDate localDate2 = LocalDate.now();
//获取时间间隔对象
Period period = Period.between(localDate1,localDate2);
//获取相隔的年
int years = period.getYears();
System.out.println(years);
//获取间隔月
int months = period.getMonths();
//获取间隔天
int days = period.getDays();
System.out.println(years+"年"+months+"月"+days+"天");
Duration类
**计算两个时间间隔的时、分、秒
//生日的时间
LocalDateTime localDate1 = LocalDateTime.of(1996, 6, 23,13,34,22);
//今天的时间
LocalDateTime localDate2 = LocalDateTime.of(1996, 7, 13,06,34,11);
//获取时间间隔对象
Duration duration = Duration.between(localDate1,localDate2);
//获取相隔的小时
long years = duration.toHours();
//获取相隔的分钟
long minutes = duration.toMinutes();
//获取相隔的秒
long seconds = duration.toSeconds();
//相隔的毫秒
long millis = duration.toMillis();
System.out.pritnln("-------------");
//获取xx天xx小时xx分钟xx秒
long daysPart = duration.toDaysPart();
int hoursPart = duration.toHoursPart();
int minutesPart = duration.toMinutesPart();
int secondsPart = duration.toSecondsPart();
System.out.println("距离双十一还有:"+daysPart+"天"+hoursPart+"小时"+minutesPart+"分钟"+secondsPart+"秒");