学习 java8 新特性之日期时间,总结一下,方便自己以后的学习查看
新建 NewDate
import lombok.extern.slf4j.Slf4j;
import java.time.*;
/**
* Java 8 日期时间 API
* 新的java.time包涵盖了所有处理日期,时间,日期/时间,时区,时刻(instants),过程(during)与时钟(clock)的操作。
*/
@Slf4j
public class NewDate {
public static void main(String[] args) {
NewDate newDate = new NewDate();
// newDate.test01();
newDate.test02();
}
/**
* LocalDateTime.now()
*/
public void test01(){
LocalDateTime now = LocalDateTime.now(); // 年月日 时分秒
log.info("当前时间:" + now);
LocalDate localDate = now.toLocalDate();
log.info("日期:" + localDate);
int year = now.getYear();
int monthValue = now.getMonthValue();
// Month month = now.getMonth();
int dayOfMonth = now.getDayOfMonth();
int hour = now.getHour();
int minute = now.getMinute();
int second = now.getSecond();
log.info("年/月/日 时:分:秒:" + year + "/" + monthValue + "/" + dayOfMonth + " " + hour + ":" + minute + ":" + second);
// 更改日期为 2022-10-11
LocalDateTime localDateTime = now.withDayOfMonth(11).withYear(2022).withMonth(10);
log.info("更改天数后的日期:" + localDateTime);
}
/**
* 日期 时间 解析字符串
*/
public void test02(){
LocalDate now01 = LocalDate.now();
log.info("日期:" + now01);
LocalTime now02 = LocalTime.now();
log.info("时间:" + now02);
// 解析字符串
LocalDate parse01 = LocalDate.parse("2022-10-12");
LocalTime parse02 = LocalTime.parse("20:15:30");
log.info("parse01: " + parse01);
log.info("parse02: " + parse02);
}
}