Java8新的日期类型
在Java8以前,Date日期API对我们非常的不友好,它无法表示日期,只能以毫秒的精试来表示时间,并且可以修改,他的线程还不是安全的。所以Java8中引入了全新的日期和时间API就是为了解决这一问题。
LocalDate,LocalTime,LocalDateTime的简单使用
使用静态工厂of,来创建一个LocalDate实例。
@Test
public void test1() {
LocalDate of = LocalDate.of(2019, 11, 11);//2019-11-11
int year = of.getYear(); //年份:2019
Month month = of.getMonth(); //月份:NOVEMBER
int dayOfMonth = of.getDayOfMonth(); //这月的第几天:11
DayOfWeek dayOfWeek = of.getDayOfWeek();//这周的第几天:MONDAY
int dayOfYear = of.getDayOfYear(); //这年的第几天:315
boolean leapYear = of.isLeapYear(); //是否是润年:false
}
使用静态工厂of,来创建一个LocalTime实例
@Test
public void test2() {
LocalTime localTime = LocalTime.of(11, 12, 13);
int hour = localTime.getHour(); //小时:11
int minute = localTime.getMinute(); //分钟:12
int second = localTime.getSecond(); //秒数:13
}
使用静态工厂of,来创建一个LocalDateTime实例
@Test
public void test3() {
//2019-11-12T13:14:15
LocalDateTime localDateTime = LocalDateTime.of(2019, 11, 12, 13, 14, 15);
//2019-11-12
LocalDate localDate = localDateTime.toLocalDate();
//13:14:15
LocalTime localTime = localDateTime.toLocalTime();
//可以从LocalDateTime获取所有的当前的信息,比如,年份,月份。。
LocalDateTime now = LocalDateTime.now(); //获取当前系统的日期,时间
}
格式化日期类型和解晰符串
@Test
public void test4() {
LocalDateTime localDateTime = LocalDateTime.now();
String format = localDateTime.format(DateTimeFormatter.BASIC_ISO_DATE);
//20191210
String format1 = localDateTime.format(DateTimeFormatter.ISO_DATE_TIME);
//2019-12-10T09:35:22.27
String format2 = localDateTime.format(DateTimeFormatter.ISO_DATE);
//2019-12-10
String format3 = localDateTime.format(DateTimeFormatter.ISO_TIME);
//09:37:52.778
//自定义规则
String format4 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//2019-12-10 09:39:18
String format5 = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//2019-12-10
String format6 = localDateTime.format(DateTimeFormatter.ofPattern("HH:mm:ss"));
//09:40:06
//解晰字符串
String mYDateTime = "2019-12-10 09:39:18";
String mYDate = "2019-12-10";
LocalDate parse = LocalDate.parse(mYDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//2019-12-10
LocalDateTime parse1 = LocalDateTime.parse(mYDateTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//2019-12-10T09:39:18
}
参考:
细节决定成败!
个人愚见,如有不对,恳请扶正!