java常用类之JDK8中新日期时间API

日期时间API的迭代:

第一代:jdk 1.0 Date类
第二代:jdk 1.1 Calendar类,一定程度上替换Date类
第三代:jdk 1.8 提出了新的一套API

前两代存在的问题举例:

可变性:像日期和时间这样的类应该是不可变的。
偏移性:Date中的年份是从1900开始的,而月份都从0开始。
格式化:格式化只对Date用,Calendar则不行。
此外,它们也不是线程安全的;不能处理闰秒等。

java 8 中新的日期时间API涉及到的包

在这里插入图片描述

本地日期、本地时间、本地日期时间的使用:LocalDate / LocalTime / LocalDateTime

① 分别表示使用 ISO-8601日历系统的日期、时间、日期和时间。它们提供了简单的本地日期或时间,并不包含当前的时间信息,也不包含与时区相关的信息。
② LocalDateTime相较于LocalDate、LocalTime,使用频率要高
③ 类似于Calendar
在这里插入图片描述

@Test
    public void test1() {
        //now(): 获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();
        System.out.println(localDate);
        System.out.println(localTime);
        System.out.println(localDateTime);

        //of():设置指定的年月日时分秒,没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2021, 2, 7, 13, 51, 41);
        System.out.println(localDateTime1);

        //getXxx()
        System.out.println(localDateTime1.getDayOfMonth());
        System.out.println(localDateTime1.getDayOfWeek());
        System.out.println(localDateTime1.getMonth());
        System.out.println(localDateTime1.getMonthValue());
        System.out.println(localDateTime1.getMinute());

        //体现不可变性
        LocalDate localDate1 = localDate.withDayOfMonth(10);
        System.out.println(localDate);
        System.out.println(localDate1);

        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);
        System.out.println(localDateTime2);

        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);
        System.out.println(localDateTime3);

        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);
        System.out.println(localDateTime4);
    }

时间点:Instant

① 时间线上的一个瞬时点。 概念上讲,它只是简单的表示自1970年1月1日0时0分0秒(UTC开始的秒数。)
② 类似于 java.util.Date类
在这里插入图片描述

@Test
    public void test2(){
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2021-02-07T06:52:44.531Z

        //添加时间的偏移量
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2021-02-07T14:55:56.410+08:00

        //toEpochMilli()获取对应的毫秒数
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli()通过给定的毫秒数,获取Instance实例
        Instant instant1 = Instant.ofEpochMilli(1612681170274L);
        System.out.println(instant1);
    }

日期时间格式化类:DateTimeFormatter

① 格式化或解析日期、时间
② 类似于SimpleDateFormat

预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
本地化相关的格式。如:ofLocalizedDateTime(FormatStyle.LONG)
自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)

在这里插入图片描述

@Test
    public void test3(){
        //方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);
        System.out.println(str1);
        //解析:字符串-->日期
        TemporalAccessor parse = formatter.parse("2021-02-07T15:10:08.717");
        System.out.println(parse);

        //方式二:
        //本地化相关的格式:ofLocalizedDateTime()
        //FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: 适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2021年2月7日 下午03时20分31秒

        //本地化相关的格式:ofLocalizedDate()
        //FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT: 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2021年2月7日 星期日

        //重点:方式三:自定义的格式。如ofPattern("yyyy-MM-dd hh:mm:ss E")
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2021-02-07 03:30:53
        //解析
        TemporalAccessor accessor = formatter3.parse("2021-02-07 03:30:53");
        System.out.println(accessor);


    }

其他API

带时区的日期时间:ZonedDateTime / ZoneId

// ZoneId:类中包含了所的时区信息
	@Test
	public void test1(){
		//getAvailableZoneIds():获取所的ZoneId
		Set<String> zoneIds = ZoneId.getAvailableZoneIds();
		for(String s : zoneIds){
			System.out.println(s);
		}
		System.out.println();
		
		//获取“Asia/Tokyo”时区对应的时间
		LocalDateTime localDateTime = LocalDateTime.now(ZoneId.of("Asia/Tokyo"));
		System.out.println(localDateTime);
		
		
	}
//ZonedDateTime:带时区的日期时间
	@Test
	public void test2(){
		//now():获取本时区的ZonedDateTime对象
		ZonedDateTime zonedDateTime = ZonedDateTime.now();
		System.out.println(zonedDateTime);
		//now(ZoneId id):获取指定时区的ZonedDateTime对象
		ZonedDateTime zonedDateTime1 = ZonedDateTime.now(ZoneId.of("Asia/Tokyo"));
		System.out.println(zonedDateTime1);
	}

时间间隔:Duration–用于计算两个“时间”间隔,以秒和纳秒为基准
在这里插入图片描述

@Test
	public void test3(){
		LocalTime localTime = LocalTime.now();
		LocalTime localTime1 = LocalTime.of(15, 23, 32);
		//between():静态方法,返回Duration对象,表示两个时间的间隔
		Duration duration = Duration.between(localTime1, localTime);
		System.out.println(duration);
		
		System.out.println(duration.getSeconds());
		System.out.println(duration.getNano());
		
		LocalDateTime localDateTime = LocalDateTime.of(2016, 6, 12, 15, 23, 32);
		LocalDateTime localDateTime1 = LocalDateTime.of(2017, 6, 12, 15, 23, 32);
		
		Duration duration1 = Duration.between(localDateTime1, localDateTime);
		System.out.println(duration1.toDays());
		
	}

日期间隔:Period --用于计算两个“日期”间隔,以年、月、日衡量
在这里插入图片描述

	@Test
	public void test4(){
		LocalDate localDate = LocalDate.now();
		LocalDate localDate1 = LocalDate.of(2028, 3, 18);
		
		Period period = Period.between(localDate, localDate1);
		System.out.println(period);
		
		System.out.println(period.getYears());
		System.out.println(period.getMonths());
		System.out.println(period.getDays());
		
		Period period1 = period.withYears(2);
		System.out.println(period1);
		
	}

日期时间校正器:TemporalAdjuster

@Test
	public void test5(){
		//获取当前日期的下一个周日是哪天?
		TemporalAdjuster temporalAdjuster = TemporalAdjusters.next(DayOfWeek.SUNDAY);
		
		LocalDateTime localDateTime = LocalDateTime.now().with(temporalAdjuster);
		System.out.println(localDateTime);
		
		//获取下一个工作日是哪天?
		LocalDate localDate = LocalDate.now().with(new TemporalAdjuster(){

			@Override
			public Temporal adjustInto(Temporal temporal) {
				LocalDate date = (LocalDate)temporal;
				if(date.getDayOfWeek().equals(DayOfWeek.FRIDAY)){
					return date.plusDays(3);
				}else if(date.getDayOfWeek().equals(DayOfWeek.SATURDAY)){
					return date.plusDays(2);
				}else{
					return date.plusDays(1);
				}
					
			}
			
		});
		
		System.out.println("下一个工作日是:" + localDate);
	}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值