java8日期操作与解读(持续更新)

一、常用方法

import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Date; public class DataTool { /** * 指定格式获取当前日期 * @param formatter * @return */ public String getCrrentDate(String formatter) { LocalDate now = LocalDate.now(); DateTimeFormatter theFormatter=DateTimeFormatter.ofPattern(formatter); return now.format(theFormatter); } /** * 日期格式化 * @param localDate * @param formatter * @return */ public String localDate2String(LocalDate localDate,String formatter) { DateTimeFormatter theFormatter=DateTimeFormatter.ofPattern(formatter); return localDate.format(theFormatter); } /** * 字符串转日期 * @param date * @param formatter * @return */ public LocalDate string2LocalDate(String date,String formatter) { DateTimeFormatter theFormatter=DateTimeFormatter.ofPattern(formatter); return LocalDate.parse(date, theFormatter); } /** * Date 转LocalDate * @param date * @return */ public LocalDate date2LocalDate(Date date) { Instant instant = date.toInstant(); return instant.atZone(ZoneId.systemDefault()).toLocalDate(); } /** * LocalDate 转 Date * @param localDate * @return */ public Date localDate2Date(LocalDate localDate) { ZoneId zoneId = ZoneId.systemDefault(); ZonedDateTimezonedDateTime=localDate.atStartOfDay(zoneId); Instant instant = zonedDateTime.toInstant(); return Date.from(instant); } /** * 获取指定月份的最后一天 * @param args */ public LocalDate getMonthLastDay(int year,int month) { return LocalDate.of(year, month, 1).plusMonths(1).minusDays(1); } /** * 判断星期几返回星期天为7 星期一为1 * @param localDate * @return */ public int getDayOfWeekCh(LocalDate localDate) { return localDate.getDayOfWeek().getValue(); } /** * 返回true 时 lda 更靠后 * @param lda * @param ldb * @return */ public Boolean comper(LocalDate lda, LocalDate ldb) { return lda.isAfter(ldb); } public static void main(String[] args) { LocalDate lda = LocalDate.of(2019, 8, 1); LocalDate ldb = LocalDate.of(2019, 7, 1); boolean rr = lda.isAfter(ldb); System.out.println(rr); }}

二、时间比较获取差值
public void test(){String time1 = "2019-06-26 19:00:00"; String time2 = "2019-06-26 19:01:31"; DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime localDateTime1 = LocalDateTime.parse(time1, dtf2); LocalDateTime localDateTime2 = LocalDateTime.parse(time2, dtf2); Duration duration = Duration.between(localDateTime1,localDateTime2); long days = duration.toDays(); //相差的天数 long hours = duration.toHours(); //相差的小时数 long minutes = duration.toMinutes(); //相差的分钟数 long millis = duration.toMillis(); //相差毫秒数 long nanos = duration.toNanos(); //相差的纳秒数 System.out.println(days); System.out.println(hours); System.out.println(minutes); System.out.println(millis); System.out.println(nanos); }

【java8日期操作与解读(持续更新)】需要注意的是:所求的值向下的单位会被舍去 比如分钟 那么相差59秒时认为相差的分钟数是0.

    推荐阅读