在java1.8中出现了LocalDateTime日期操作api,不得不说确实比之前的date好用得多。好了,既然好用我们就来看一下他到底如何使用吧。
1.获取当前时间
System.out.println(LocalDateTime.now());
2.格式化日期
//java1.7
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
System.out.println(sdf.format(date));
//java1.8
LocalDateTime localDateTime = LocalDateTime.now();
System.out.println(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss")));
3.获取当前毫秒值
//java1.7
System.out.println(Calendar.getInstance().getTimeInMillis());
System.out.println(System.currentTimeMillis());
//java1.8
System.out.println(Clock.systemDefaultZone().millis());
//使用localDateTime获取当前毫秒值
System.out.println(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli());
4.自定义localDateTime日期
System.out.println(LocalDateTime.of(2021, 10, 28, 16, 22, 50))
5.获取年月日时分秒
//java1.7
Calendar calendar = Calendar.getInstance();
//年
System.out.println(calendar.get(Calendar.YEAR));
//月0-11
System.out.println(calendar.get(Calendar.MONDAY) + 1);
//日
System.out.println(calendar.get(Calendar.DATE));
//时 0-12
System.out.println(calendar.get(Calendar.HOUR));
//时 0-24
System.out.println(calendar.get(Calendar.HOUR_OF_DAY));
//分
System.out.println(calendar.get(Calendar.MINUTE));
//秒
System.out.println(calendar.get(Calendar.SECOND));
//java 1.8
LocalDateTime ldt = LocalDateTime.now();
//年
System.out.println(ldt.getYear());
//月(英文)1-12
System.out.println(ldt.getMonth());
//月(数字)1-12
System.out.println(ldt.getMonthValue());
//日(以年计算)1-365
System.out.println(ldt.getDayOfYear());
//日(以月计算)1-30
System.out.println(ldt.getDayOfMonth());
//时
System.out.println(ldt.getHour());
//分
System.out.println(ldt.getMinute());
//秒
System.out.println(ldt.getSecond());
6.获取当天的起始日期 00:00:00
System.out.println(LocalDateTime.of(LocalDateTime.now().getYear(), LocalDateTime.now().getMonth(), LocalDateTime.now().getDayOfMonth(), 0, 0, 0));
7.获取当前最后日期 23:59:59
System.out.println(LocalDateTime.of(LocalDateTime.now().getYear(), LocalDateTime.now().getMonth(), LocalDateTime.now().getDayOfMonth(), 23, 59, 59));
8.给当前日期添加2小时
System.out.println(LocalDateTime.now().plusHours(2));
9.给当前日期减少2小时
System.out.println(LocalDateTime.now().minusHours(2))
10.比较两个日期大小
LocalDateTime time = LocalDateTime.of(2017, 7, 12, 15, 12, 12);
//判断是否在time时间之前
System.out.println(LocalDateTime.now().isBefore(time));
//判断是否在time时间之后
System.out.println(LocalDateTime.now().isAfter(time));