LocalDate类
第一种:直接生成当前时间
LocalDate date = LocalDate.now(); System.out.println(date); 结果:2020-08-20第二种:使用 LocalDate.of 构建时间
LocalDate date = LocalDate.now(); date = LocalDate.of(2020, 9, 20); System.out.println(date); 结果:2020-09-20第三种:使用 LocalDate.parse 构建时间
LocalDate date = LocalDate.now(); date = LocalDate.parse("2020-08-20"); System.out.println(date);LocalTime类
第一种:直接获取当前时间包含毫秒数
// 获取当前时间,包含毫秒数 LocalTime now = LocalTime.now(); System.out.println(now); 结果:10:59:01.532第二种:构建时间
LocalTime localTime = LocalTime.of(13, 30, 59); System.out.println(localTime); 结果:13:30:59第三种:获取当前时间不包含毫秒数
LocalTime now = LocalTime.now(); LocalTime localTime = now.withNano(0); System.out.println(localTime);结果:11:02:07第四种:将字符串转成时间
LocalTime localTime = LocalTime.parse("11:05:20"); System.out.println(localTime);结果:11:05:20第五种:获取时、分、秒、纳秒
LocalTime time = LocalTime.now(); System.out.println("当前时间" + time); // 获取 时,分,秒,纳秒 int hour = time.getHour(); int minute = time.getMinute(); int second = time.getSecond(); int nano = time.getNano(); System.out.println( hour + "时" + minute + "分" + second + "秒" + nano + "纳秒");结果:当前时间11:27:14.16111时27分14秒161000000纳秒外汇名词解释https:///definitions
LocalDateTime类
第一种:直接获取当前时间包含毫秒数
LocalDateTime time = LocalDateTime.now(); System.out.println(time);结果:2020-08-20T11:07:45.217第二种:将字符串转成时间
String date = "2020-08-20 11:08:10"; DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.parse(date, dateTimeFormatter); System.out.println(time);结果:2020-08-20T11:08:10第三种:将时间转成时间戳
String date="2020-08-20 11:08:10"; DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime time = LocalDateTime.parse(date, dateTimeFormatter); long l = time.toEpochSecond(ZoneOffset.of("+9")); System.out.println(l);结果:1597889290第四种:将时间进行格式化为字符串
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String time = dateTimeFormatter.format(LocalDateTime.now()); System.out.println(time);结果:2020-08-20 11:13:39第五种:获取、年、月、日、时、分、秒、纳秒
/** 时间 **/ LocalDateTime dateTime = LocalDateTime.now(); System.out.println("LocalDateTime:" + dateTime); // LocalDateTime实际上就是 日期类+时间类的组合,所以也可以LocalDate和LocalTime的一些方法 int year = dateTime.getYear(); int month = dateTime.getMonthValue(); int day = dateTime.getDayOfMonth(); int hour = dateTime.getHour(); int minute = dateTime.getMinute(); int second = dateTime.getSecond(); int nano = dateTime.getNano(); System.out.println(year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒" + nano + "纳秒");结果:当前时间:2020-08-20T11:32:10.9782020年8月20日11时32分10秒978000000纳秒总结
到此这篇关于Java8生成时间方式及格式化时间的文章就介绍到这了,更多相关Java8生成时间方式及格式化时间内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!