1.format:转 String;parse:String 转
正确:DateTime date = DateUtil.parse("2023-08-01");
错误:这种表达方式生成的date只会是1月1日
DateTime date = DateUtil.parse("2023-08-01", "YYYY-MM-dd");
String string = DateUtil.format(DateTime, "YYYY-MM-dd");
2. DateUtil工具类
DateTime date = DateUtil.beginOfMonth(DateUtil.parse(month + "-01"));//当月开始时间
DateTime date = DateUtil.endOfMonth(date);// 当月结束时间
//月份减一
DateTime preMonth = DateUtil.offsetMonth(new DateTime(), -1);
等价于
DateUtil.offset(new DateTime(),DateField.MONTH,-1);
DateTime startDate = DateUtil.beginOfYear(preMonth);//当前参数年份开始时间
DateTime endDate = DateUtil.endOfYear(preMonth);//当前参数年份结束时间
//两个参数间隔月份组成数组
List<DateTime> dates = DateUtil.rangeToList(startDate,endDate, DateField.MONTH);
3.LocalDate工具类
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String bgdate = dtf.format(LocalDate.now());
LocalDate localDate = LocalDate.parse(bgdate, dtf);
LocalDate.now()只能获取当前日期
LocalDate.of(2025,9,8);可以得到指定参数的日期
//当前日期 + 一周(更多选项可以查看 Java 8 API 中的 ChronoUnit 类。)
localDate.plus(1,ChronoUnit.WEEKS);
4.LocalDateTime工具类
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String s = LocalDateTime.now().format(formatter);
LocalDateTime time = LocalDateTime.parse("",formatter)
5.String转Date
Date date = DateTime.parse(String).toDate();
6.Java8特性:
类名称 | 描述 |
---|
Instant | 时间戳 |
Duration | 持续时间,时间差 |
LocalDate/LocalTime==LocalDateTime | 日期时间 |
Period | 时间段 |
ZoneOffset | 时间偏移量,比如:=8:00 |
ZonedDateTime | 带时区的时间 |
Clock | 时钟 |
检查像生日这种周期性事件
LocalDate now = LocalDate.now();
LocalDate nyr = LocalDate.of(2024,8,7);
MonthDay birthday = MonthDay.of(nyr.getMonth(),nyr.getDayOfMonth());
MonthDay currentMonthDay = MonthDay.from(now);
String s;
if(currentMonthDay.equals(birthday)){
s = "是你的生日";
}else{
s = "你的生日还没到";
}
处理时区
ZoneId america = ZoneId.of("America/New_York");
LocalDateTime localDateTime = LocalDateTime.now();
ZonedDateTime dateAndTimeInNewYork = ZonedDateTime.of(localDateTime,america);
判断闰年
LocalDate today = LocalDate.now();
String s;
if(today.isLeapYear()){
s = "is";
}else{
s = "not";
}
获取当前时间戳
Instant timestamp = Instant.now();
timestamp.toEpochMilli();
时间戳中包含日期和时间,类似Date
Date.from(Instant);Instant 转成 Date
Date.toInstant(); Date 转成 Instant