java中时间处理

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值