java8 时间操作
Instant 时间戳
Duration 持续时间、时间差
LocalDate 只包含日期,比如:2018-09-24
LocalTime 只包含时间,比如:10:32:10
LocalDateTime 包含日期和时间,比如:2018-09-24 10:32:10
Peroid 时间段
ZoneOffset 时区偏移量,比如:+8:00
ZonedDateTime 带时区的日期时间
Clock 时钟,可用于获取当前时间戳
java.time.format.DateTimeFormatter 时间格式化类
获取当前时间 LocalDateTime time = LocalDateTime.now();
日期格式:DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
java8当前时间转String字符串:String tm = time.format(formatter);
将Date时间转为String:Date date = new Date();
Instant instant =date.toInstant();
ZoneId zoneId = ZoneId.systemDefault();
LocalDateTime localDateTime =LocalDateTime.ofInstant(instant,zoneId);
String tm = formatter.format(localDateTime);
将String转为Date类型:String tm8="2020-11-11 08:00:00";
LocalDateTime localDateTime=LocalDateTime.parse(tm8,formatter);
ZoneId zoneId = ZoneId.systemDefault();
Instant instant = localDateTime.atZone(zoneId).toInstant();
Date btm = Date.from(instant);
LocalDate 转Date类型:LocalDate localDate =LocalDate.now();
ZonedDateTime zonedDateTime = dateTime.atStartOfDay(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
Date btm = Date.from(instant);
如果是string类型的LocalDate只需要将String转为LocalDate,如
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate dateTime = LocalDate.parse(stringtm, dateTimeFormatter);
LocalDate.parse(stringtm,dateTimeFormatter );
Date转LocalDate:
Date date = new Date();
Instant instant = date.toInstant();
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
LocalDate localDate = zdt.toLocalDate();
一天中最早时间和最晚时间:
LocalDateTime startTm = LocalDateTime.of(LocalDate.now(),LocalTime.MIN);//2020-11-11 00:00:00
LocalDateTime endTm = LocalDateTime.of(LocalDate.now(),LocalTime.MAX);//2020-11-11 23:59:59
一个月第一天0点到一个月最后一天23:59:59
DateTimeFormatter da = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime monthTM = LocalDateTime.of(LocalDate.parse(tm + "-01", da), LocalTime.MIN); //tm为字符串类型 2020-11
LocalDateTime min = monthTM.with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0);
LocalDateTime max = monthTM.with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
一年中第一天0点到最后一天23:59:59
DateTimeFormatter da = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime monthY = LocalDateTime.of(LocalDate.parse(tm + "-01-01", da),LocalTime.MIN); //tm为字符串 2020
LocalDateTime min = monthY.with(TemporalAdjusters.firstDayOfYear()).withHour(0).withMinute(0).withSecond(0);
LocalDateTime max = monthY.with(TemporalAdjusters.lastDayOfYear()).withHour(23).withMinute(59).withSecond(59);
遇到一问题,当把上面的min,max转为Date类型时,ZoneId zoneId = ZoneId.systemDefault(); Instant Sinstant = min.atZone(zoneId).toInstant(); Instant Einstant = max.atZone(zoneId).toInstant(); Instant这里的值比min,max少8个小时,当转为Date时,自动补齐8个小时 Date startTime = Date.from(Sinstant); Date endTime = Date.from(Einstant); 这里的时间恢复正常,应该和ZoneId涉及的时区有关
本文地址:https://blog.csdn.net/luwei_cool/article/details/109613052