一、JDK7 的日期 和 JDK8 的日期对比
JDK7 创建一个时间
Date date0 = new Date();
JDK8 创建一个时间
LocalDate today = LocalDate.now();
我们先看看这执行出来都是啥?
Date输出:
Wed Apr 13 13:19:06 CST 2022
LocalDate输出:
2022-04-13
首先我们从输出上,直接就感觉有点难受,Date输出的看起来就不是那么的直观,所以,当你想要直观的去输出这个时间的时候,可能就得用到 SimpleDateFormat 去格式化一下我们的这个时间。但是如果是用 LocalDate 就不会有这种顾虑了。
Date格式化:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
String str = sdf.format(date0);
JDK1.8之后我们可以使用 java.time.format.DateTimeFormatter来进行日期时间的格式化。
LocalDate now = LocalDate.now();
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String JDK8Time = now.format(dateTimeFormatter);
System.out.println("JDK8格式化后的时间数据=="+JDK8Time);
二、SimpleDateFormat & DateTimeFormatter
SimpleDateFormat
是个线程不安全的,使用的时候,只能在方法内部创建新的局部变量。而DateTimeFormatter
不但是不变对象,它还是线程安全的。所以DateTimeFormatter
可以只创建一个实例,到处引用。
三、JDK8日期的各种用法
3.1 LocalDate转String
LocalDate localDate = LocalDate.now();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String dateStr = localDate.format(fmt);
System.out.println("LocalDate转String:" + dateStr);
转换结果
LocalDate转String:2022/04/14
3.2 Date转LocalDateTime
Date date = new Date();
LocalDateTime localDateTime = (date).toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
System.out.println("localDateTime=" + localDateTime);
转换结果
localDateTime=2022-10-25T09:50:06.506
3.3 时间戳转LocalDateTime
long timestamp = System.currentTimeMillis();
Instant instant1 = Instant.ofEpochMilli(timestamp);
System.out.println("时间戳 转 LocalDateTime:" + LocalDateTime.ofInstant(instant1, ZoneId.systemDefault()));
转换结果
时间戳 转 LocalDateTime:2022-04-14T10:09:14.780
3.4 LocalDateTime转时间戳
long now = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
long end = LocalDateTime.of(LocalDate.from(LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth())), LocalTime.MAX).toEpochSecond(ZoneOffset.of("+8"));
3.5 String 转 LocalDateTime
//String 转 LocalDateTime
LocalDateTime date = LocalDateTime.parse("2022-06-01"+" 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
3.6 LocalDateTime本月开始/结束时间
//LocalDateTime 本月开始时间 2022-06-01T00:00
LocalDateTime startDateTime = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).with(LocalTime.MIN);
//LocalDateTime 本月结束时间 2022-06-30T23:59:59.999999999
LocalDateTime endDateTime = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).with(LocalTime.MAX);
3.7 LocalDate今天/昨天/明天/下周
//今天:2022-06-07
System.out.println(LocalDate.now());
//昨天:2022-06-06
System.out.println(LocalDate.now().plusDays(-1));
//明天:2022-06-08
System.out.println(LocalDate.now().plusDays(1));
//下周:2022-06-14
System.out.println(LocalDate.now().plusWeeks(1));
3.8 LocalDateTime 转 LocalDate
LocalDateTime time = LocalDateTime.now();
LocalDate day = time.toLocalDate();
3.9 LocalDate本月开始/结束时间
LocalDate day = LocalDate.now();
//本月开始日期
LocalDate startDay = day.with(TemporalAdjusters.firstDayOfMonth());
//本月结束日期
LocalDate endDay = day.with(TemporalAdjusters.lastDayOfMonth());
四、转换
//1.LocalDate转Date
LocalDate nowLocalDate = LocalDate.now();
Date date = Date.from(localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant());
//2.LocalDateTime转Date
LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());
//3.Date转LocalDateTime(LocalDate)
Date date =newDate();
LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();
//4.LocalDate转时间戳
LocalDate localDate = LocalDate.now();
longtimestamp = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
//5.LocalDateTime转时间戳
LocalDateTime localDateTime = LocalDateTime.now();
longtimestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
//6.时间戳转LocalDateTime(LocalDate)
longtimestamp = System.currentTimeMillis();
LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDate();
LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
//7.LocalDateTime 转 LocalDate
LocalDateTime time = LocalDateTime.now();
LocalDate day = time.toLocalDate();
五、获取两个日期中间的所有天数,所有月份
5.1 LocalDate
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class Client {
public static void main(String[] args) {
LocalDate startDay = LocalDate.parse("2022-07-01");
LocalDate endDay = LocalDate.parse("2022-08-01");
List<String> day = getBetweenDate(startDay.toString(), endDay.toString(),1);
//System.out.println("day = " + day);
List<String> month = getBetweenDate("2022-07", "2022-11",2);
System.out.println("month = " + month);
}
/**
* 获取两个日期中间的所有天数,所有月份
* @param start
* @param end
* @param type
* @return
*/
public static List<String> getBetweenDate(String start, String end, Integer type) {
List<String> list = new ArrayList<>();
if(start.length()<8){
start+="-01";
end+="-01";
}
LocalDate startDate = LocalDate.parse(start);
LocalDate endDate = LocalDate.parse(end);
long distance = 0L;
if (type == 1) {
distance = ChronoUnit.DAYS.between(startDate, endDate);
Stream.iterate(startDate, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f.toString()));
} else if(type==2) {
distance = ChronoUnit.MONTHS.between(startDate, endDate);
Stream.iterate(startDate, d -> d.plusMonths(1)).limit(distance + 1).forEach(f -> list.add(f.toString().substring(0,7)));
}
return list;
}
}
5.2 LocalDateTime
public class LocalDateTimeUtil {
public LocalDateTimeUtil() {
throw new RuntimeException("工具类,不用创建");
}
/**
* 获取两个日期中间的所有天数
*
* @return
*/
public static List<LocalDateTime> listBetweenDate(String startDayStr, String endDayStr) {
String[] startArray = startDayStr.split(" ");
String[] endArray = endDayStr.split(" ");
String start = startArray[0];
String startTime = startArray[1];
String end = endArray[0];
String endTime = endArray[1];
if (startTime.equals(endTime)) {
//如果时间相同,则不用拆开处理了,
LocalDateTime startDay = LocalDateTime.parse(startDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime endDay = LocalDateTime.parse(endDayStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
return listBetweenDate(startDay, endDay);
} else {
//"2022-11-04 19:30:00", "2022-11-05 16:30:00" 需要拆开比较,不然只会返回一天,出现BUG
LocalDateTime startDay = LocalDateTime.parse(start + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime endDay = LocalDateTime.parse(end + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
List<LocalDateTime> dayTimeList = listBetweenDate(startDay, endDay);
List<LocalDateTime> newDayTimeList = new ArrayList<>();
for (LocalDateTime item : dayTimeList) {
LocalDateTime newDayTime = LocalDateTime.of(item.toLocalDate(), LocalTime.parse(startTime));
newDayTimeList.add(newDayTime);
}
newDayTimeList.remove(dayTimeList.size() - 1);
LocalDateTime lastDayTime = dayTimeList.get(dayTimeList.size() - 1);
LocalDateTime lastNewDayTime = LocalDateTime.of(lastDayTime.toLocalDate(), LocalTime.parse(endTime));
newDayTimeList.add(lastNewDayTime);
return newDayTimeList;
}
}
/**
* 获取两个日期中间的所有天数
*
* @return
*/
public static List<LocalDateTime> listBetweenDate(LocalDateTime startDay, LocalDateTime endDay) {
List<LocalDateTime> list = new ArrayList<>();
long distance = ChronoUnit.DAYS.between(startDay, endDay);
Stream.iterate(startDay, d -> d.plusDays(1)).limit(distance + 1).forEach(f -> list.add(f));
return list;
}
}
测试
public class Test {
public static void main(String[] args) {
List<LocalDateTime> timeList = LocalDateTimeUtil.listBetweenDate("2022-11-04 19:30:00", "2022-11-05 16:30:00");
//[2022-11-04T19:30, 2022-11-05T16:30]
System.out.println(timeList);
}
}
六、设置日期的最后时间
public static void main(String[] args) {
//2022-10-13
LocalDate today = LocalDate.now();
System.out.println(today);
//2022-10-13 23:59:59
LocalDateTime todayLastTime = today.atTime(23,59,59);
System.out.println(todayLastTime);
}
七、LocalDateTime两个时间相差的天数,小时数,分钟数,毫秒数
public static void main(String[] args) {
LocalDateTime start = LocalDateTime.of(2022, 5, 7, 1, 1);
LocalDateTime end = LocalDateTime.of(2022, 5, 8, 1, 1);
System.out.println("相差的天数: " + Duration.between(start, end).toDays() + "天");
System.out.println("相差的小时数: " + Duration.between(start, end).toHours() + "小时");
System.out.println("相差的分钟数: " + Duration.between(start, end).toMinutes() + "分钟");
System.out.println("相差的毫秒数: " + Duration.between(start, end).toMillis() + "毫秒");
}
运行结果
相差的天数: 1天
相差的小时数: 24小时
相差的分钟数: 1440分钟
相差的毫秒数: 86400000毫秒
八、LocalDateTime时间加减法
LocalDateTime time = LocalDateTime.now();
time = time.plusMinutes(5);//获取当前时间并加5分钟
time = time.minusMinutes(5);//获取当前时间并减去5分钟
time = time.plusHours(5);//获取当前时间并加5小时
time = time.minusHours(5);//获取当前时间并减去5小时
九、当天开始/结束时间
public static void main(String[] args) {
LocalDateTime date = LocalDateTime.parse("2022-11-09" + " 12:32:01", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LocalDateTime dateStart = LocalDateTime.of(date.toLocalDate(), LocalTime.MIN);
LocalDateTime dateEnd = LocalDateTime.of(date.toLocalDate(), LocalTime.MAX);
System.out.println(dateStart);
System.out.println(dateEnd);
String dayStr = date.toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime dataEnd2 = LocalDateTime.parse(dayStr + " " + "23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
System.out.println(dataEnd2);
}
网友评论