java 日期时间操作(二) java8操作

一、摘要

java8之前,我们使用Date和Calendar类来进行日期时间操作。但是java.util.Date 是非线程安全的,所有的日期类都是可变的,这是Java日期类最大的问题之一。所以Java8使用一套新的日期操作API来处理日期时间。例如:Local(本地) − 简化了日期时间的处理,没有时区的问题;Zoned(时区) − 通过制定的时区处理日期时间。

二、LocalDate类和和LocalTime类

LocalDate类的实例是一个不 可变对象,它只提供了简单的日期,并不含当天的时间信息。另外,它也不附带任何与时区相关的信息。LocalTime用来表示一天中的时间。
1、获取当前日期和时间

LocalDate date = LocalDate.now();    //当前日期
LocalTime time = LocalTime.now();    //当前时间
System.out.println("当前日期和时间:"+date.toString()+" "+time.toString());    //输出示例:当前日期和时间:2020-04-21 17:05:25.477

2、创建LocalDate类和和LocalTime类对象

//方法一:通过of方法创建
LocalDate ofDate = LocalDate.of(2020, 4, 21);//2020-04-21
LocalTime ofTime = LocalTime.of(17, 21, 30); // 17:21:30
System.out.println("of方法创建的日期和时间:"+ofDate+" "+ofTime);

//方法二:使用parse来创建
LocalDate parseDate = LocalDate.parse("2020-04-21");//2020-04-21
LocalTime parseTime = LocalTime.parse("17:21:30");// 17:21:30
System.out.println("parse方法创建的日期和时间:"+parseDate+" "+parseTime);

3、获取LocalDate和LocalTime对象常用值

int year = ofDate.getYear(); 	//年
Month month = ofDate.getMonth(); 	//月
int day = ofDate.getDayOfMonth(); 	//日 在当前月的第几日
DayOfWeek dow = ofDate.getDayOfWeek(); 	//星期几
int len = ofDate.lengthOfMonth(); 	//本月天数
int len1 = ofDate.lengthOfYear()	//本年天数
boolean leap = ofDate.isLeapYear(); 
System.out.println("年:"+year);
System.out.println("月:"+month);
System.out.println("日:"+day);
System.out.println("星期:"+dow);
System.out.println("本月天数:"+len);
System.out.println("是否为闰年:"+leap);

int y = ofDate.get(ChronoField.YEAR);
int m = ofDate.get(ChronoField.MONTH_OF_YEAR);
int d = ofDate.get(ChronoField.DAY_OF_MONTH);
int dow2 = ofDate.get(ChronoField.DAY_OF_WEEK);

int hour2 = ofTime.get(ChronoField.HOUR_OF_DAY);
int minute2 = ofTime.get(ChronoField.MINUTE_OF_HOUR);
int second2 = ofTime.get(ChronoField.SECOND_OF_MINUTE);
        
System.out.println("年:"+y);
System.out.println("月:"+m);
System.out.println("日:"+d);
System.out.println("星期几:"+dow2);
        
System.out.println("时:"+hour2);
System.out.println("分:"+minute2);
System.out.println("秒:"+second2);

4、日期时间计算
Java8提供了新的plusXxx()方法用于计算日期时间增量值,替代了原来的add()方法。新的API将返回一个全新的日期时间示例,需要使用新的对象进行接收。

        LocalDate date = LocalDate.now();
        LocalDate newDate1 = date.plus(2, ChronoUnit.WEEKS);//按周增加
        System.out.println(newDate1);
        LocalDate newDate2 =  date.plusDays(-2);   //按天数增加
        System.out.println(newDate2);
        LocalDate newDate3 =  date.plusMonths(2);     //按月增加
        System.out.println(newDate3);
        LocalDate newDate4 =  date.plusWeeks(2);    //按周增加
        System.out.println(newDate4);
        LocalDate newDate5 =  date.plusYears(2);    //按年增加
        System.out.println(newDate5);
        
        LocalTime time = LocalTime.of(17, 21, 30);
        LocalTime newTime1 = time.plus(1, ChronoUnit.MINUTES);//按分增加
        System.out.println(newTime1);
        LocalTime newTime2 = time.plusHours(-1);//按时增加
        System.out.println(newTime2);
        LocalTime newTime3 = time.plusMinutes(3);    //按分增加
        System.out.println(newTime3);
        LocalTime newTime4 = time.plusSeconds(50);    //按秒增加
        System.out.println(newTime4);

5、日期时间比较
Java8提供了isAfter()、isBefore()用于判断当前日期时间和指定日期时间的比较

        LocalDate now = LocalDate.now();
        
        LocalDate date1 = LocalDate.of(2000, 1, 1);
        if (now.isAfter(date1)) {
            System.out.println("2000已经过去了");
        }
        
        LocalDate date2 = LocalDate.of(2022, 1, 1);
        if (now.isBefore(date2)) {
            System.out.println("2022年还未到来");
        }

三、LocalDateTime类

LocalDateTime类,即包含了日期也包含了时间,可以看成是LocalDate和LocalTime的组合。但不包含时区信息。

LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);

//创建LocalDateTime对象
LocalDateTime dt1 = LocalDateTime.of(2020, Month.MARCH, 18, 13, 45, 20);
LocalDate date = LocalDate.now();
LocalTime time = LocalTime.now();
LocalDateTime dt2 = LocalDateTime.of(date, time);
System.out.println(dt1);
System.out.println(dt2);

LocalDateTime currentTime = LocalDateTime.now();
System.out.println("当前时间: " + currentTime);
LocalDate date1 = currentTime.toLocalDate();
System.out.println("date1: " + date1);
//Month month = currentTime.getMonth();
int month = currentTime.getMonthValue();
System.out.println("当前月: " + month);
int day = currentTime.getDayOfMonth();
System.out.println("当前日: " + day);
int hour = currentTime.getHour();
System.out.println("当前时: " + hour);
	    
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);//设置年份和当月日期
System.out.println("date2: " + date2);

四、带时区信息的日期时间

 // 获取当前时间日期
ZonedDateTime dateTime = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");
System.out.println("date1: " + dateTime);

ZoneId id = ZoneId.of("Europe/Paris");
System.out.println("ZoneId: " + id);

ZoneId currentZone = ZoneId.systemDefault();
System.out.println("当期时区: " + currentZone);


// 上海时间
ZoneId shanghaiZoneId = ZoneId.of("Asia/Shanghai");
ZonedDateTime shanghaiZonedDateTime = ZonedDateTime.now(shanghaiZoneId);

// 东京时间
ZoneId tokyoZoneId = ZoneId.of("Asia/Tokyo");
ZonedDateTime tokyoZonedDateTime = ZonedDateTime.now(tokyoZoneId);

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println("上海时间: " + shanghaiZonedDateTime.format(formatter));
System.out.println("东京时间: " + tokyoZonedDateTime.format(formatter));

五、日期格式化DateTimeFormatter类

新的 java.time.format 包就是格式化以及解析日期、时间对象的。这个包中最重要的是DateTimeFormatter。
使用预定义格式解析与格式化日期:

// 解析日期
String dateText = "20180924";
LocalDate localdate = LocalDate.parse(dateText, DateTimeFormatter.BASIC_ISO_DATE);
System.out.println("格式化之后的日期=" + localdate);
        
// 格式化日期
dateText = localdate.format(DateTimeFormatter.ISO_LOCAL_DATE);    //yy-MM-dd
System.out.println("ISO_LOCAL_DATE:" + dateText);
dateText = localdate.format(DateTimeFormatter.BASIC_ISO_DATE);    //yyMMdd
System.out.println("BASIC_ISO_DATE:" + dateText);

日期和字符串的相互转换:

        //将时间转换为字符串
        LocalDate date = LocalDate.now();
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
		DateTimeFormatter chinaFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
		String str1 = date.format(formatter);// dd/MM/yyyy
		String str2 = date.format(chinaFormatter);// yyyy年MM月dd日 星期二
		System.out.println(str1);
		System.out.println(str2);

		// 将字符串转换为时间
		LocalDate date1 = LocalDate.parse("20200421", DateTimeFormatter.BASIC_ISO_DATE);
		LocalDate date2 = LocalDate.parse("2020-04-21", DateTimeFormatter.ISO_LOCAL_DATE);
		LocalDate date3 = LocalDate.parse("21/04/2020", formatter);
		LocalDate date5 = LocalDate.parse("2020年4月21日 星期二", chinaFormatter);
		System.out.println(date1);
		System.out.println(date2);
		System.out.println(date3);
		System.out.println(date5);

		// 3. 自定义DateTimeFormatter

		DateTimeFormatter complexFormatter = new DateTimeFormatterBuilder().appendText(ChronoField.DAY_OF_MONTH)
				.appendLiteral(". ").appendText(ChronoField.MONTH_OF_YEAR).appendLiteral(" ")
				.appendText(ChronoField.YEAR).parseCaseInsensitive().toFormatter(Locale.CHINA);
		String str = date.format(complexFormatter);
		System.out.println(str);

参考

https://blog.csdn.net/wangdong5678999/article/details/81159690
https://www.cnblogs.com/ark-blog/p/9694950.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值