java8新日期时间使用详解


老的java date已成过去式,存在诸多弊端,建议废弃使用,今天来和大家一起学习新日期时间使用方法。

一、日期时间

//瞬时实例,表示一个时间点,和时区无关,相当于旧的date,通常用于表示时间戳。
Instant instant=Instant.now();//获取系统当前时间

//本地日期,不包含具体时间
LocalDate localDate=LocalDate.now();
//获取任意日期,用LocalDate.of()方法
LocalDate localDate=LocalDate.of(2024,03,12);

//本地时间,不包含日期
LocalTime localTime=LocalTime.now();

//不带时区信息的日期和时间,不能直接转换成时间戳。
LocalDateTime localDateTime=LocalDateTime.now();
//带时区信息的日期和时间,相当于旧的Calendar。
ZonedDateTime zonedDateTime=ZonedDateTime.now();

二、日期时间转换方法

//新日期转换成旧date,使用Date.from(Instant)方法。
Date date=Date.from(instant);

//旧date转换成新日期,使用date.toInstant()方法
Instant instant= date.toInstant();

//新日期转换成java.sql.Timestamp,使用java.sql.Timestamp.from(instant)方法
java.sql.Timestamp timestamp=java.sql.Timestamp.from(instant);

//新日期时间转换成字符串格式,用formate()方法
public static String dateFormat(LocalDateTime date, String dateFormat) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(dateFormat);
    return date.format(formatter);
}

//旧日期时间转换成字符串格式
public static String dateFormat(Date date, String dateFormat) {
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    return formatter.format(date);
}

//字符串日期转换成新时间对象,用parse()方法
LocalDateTime localDateTime=LocalDateTime.parse(str,ofPattern);

三、时区

//ZoneId类,代替j旧的TimeZone
//根据"区域/城市"字符串创建一个时区对象
ZoneId zoneId=ZoneId.of("Asia/Shanghai");
//获取系统默认时区对象
ZoneId zoneId=ZoneId.systemDefault();

//获取所有合法的"区域/城市"字符串
Set<String> set= ZoneId.getAvailableZoneIds();

//将老的TimeZone转换成新的ZoneId
 ZoneId zoneId = TimeZone.getDefault().toZoneId();
 
//将LocalDateTime转换成ZonedDateTime
ZonedDateTime zonedDateTime=ZonedDateTime.of(localDateTime,zoneId);
  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值