测试类:
import java.time.*; import java.time.format.DateTimeFormatter; public class App { public static void main( String[] args ) { LocalDateTime time = LocalDateTime.now(); System.out.println(time.toString()); //输出日期时间:2019-05-04T18:27:55.240 System.out.println(time.toLocalDate()); //输出日期:2019-05-04 System.out.println(time.toLocalTime()); //输出时间:18:27:55.240 System.out.println(time.getDayOfMonth()); //输出当前日期月份的第几天:4 System.out.println(time.getDayOfWeek()); //输出档期日期周几:SATURDAY System.out.println(time.getDayOfYear()); //当前日期在该年属于第几天:124 System.out.println(time.getHour()); //输出:18 System.out.println(time.getMinute()); //输出:27 System.out.println(time.getSecond()); //输出:55 System.out.println(time.getMonthValue()); //输出:5 System.out.println(time.getMonth()); //输出:MAY System.out.println("=============================================="); //格式化输出: DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"); System.out.println(time.format(format)); //输出:2019-05-04 18:27:55 //构造时间 LocalDateTime startTime = LocalDateTime.of(2019,05,04,17,59); System.out.println(startTime.format(format)); //输出:2019-05-04 17:59:00 LocalDateTime endTime = LocalDateTime.of(LocalDate.now(), LocalTime.of(0,0,0)); System.out.println(endTime.format(format)); //输出:2019-05-04 00:00:00 //时间比较 System.out.println(time.isAfter(startTime)); //输出:true System.out.println(time.isBefore(endTime)); //输出:false //时间运算 System.out.println(time.plusDays(-1).format(format)); //输出:2019-05-03 18:27:55 System.out.println(time.plusDays(1).format(format)); //输出:2019-05-05 18:27:55 System.out.println(time.plusMonths(-1).format(format)); //输出:2019-04-04 18:27:55 System.out.println(time.plusMonths(1).format(format)); //输出:2019-06-04 18:27:55 System.out.println(time.getHour()); //输出:18 System.out.println(time.withHour(1).format(format)); //输出:2019-05-04 01:27:55 //获取毫秒数时间戳 long milliSec = time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); System.out.println(milliSec); //输出:1556965675240 //获取秒数时间戳 long sec = time.atZone(ZoneId.systemDefault()).toInstant().getEpochSecond(); System.out.println(sec); //输出:1556965675 //时间戳转换为时间 LocalDateTime time2 =LocalDateTime.ofInstant(Instant.ofEpochMilli(milliSec),ZoneId.systemDefault()); System.out.println(time2.format(format)); //输出:2019-05-04 18:27:55 LocalDateTime time3 = LocalDateTime.ofInstant(Instant.ofEpochSecond(sec),ZoneId.systemDefault()); System.out.println(time3.format(format)); //输出:2019-05-04 18:27:55 } }
输出结果:
2019-05-04T18:27:55.240
2019-05-04
18:27:55.240
4
SATURDAY
124
18
27
55
5
MAY
==============================================
2019-05-04 18:27:55
2019-05-04 17:59:00
2019-05-04 00:00:00
true
false
2019-05-03 18:27:55
2019-05-05 18:27:55
2019-04-04 18:27:55
2019-06-04 18:27:55
18
2019-05-04 01:27:55
1556965675240
1556965675
2019-05-04 18:27:55
2019-05-04 18:27:55