LocalDateTime类的使用

Java的Date,Calendar类型使用起来并不是很方便,而且Date类(据说)有着线程不安全等诸多弊端。同时若不进行封装,会在每次使用时特别麻烦。于是Java8推出了线程安全、简易、高可靠的时间包。并且数据库中也支持LocalDateTime类型,在数据存储时候使时间变得简单。Java8这次新推出的包括三个相关的时间类型:LocalDateTime年月日十分秒;LocalDate日期;LocalTime时间;三个包的方法都差不多。

使用Date的弊端

  1. 使用Date输出的日期可读性差(在不进行日期格式化的情况下)
	Tue Sep 10 09:34:04 CST 2019
  1. 在对Date使用SimpleDateFormat进行日期时间格式化时我们需要明确的知道,SimpleDateFormat是线程不安全的,在高并发高负载的情况下使用,极容易引发线程安全性问题,以下是SimpleDateFormat的format方法源码:
private StringBuffer format(Date date, StringBuffer toAppendTo,
                              FieldDelegate delegate) {
        // Convert input date to time field list
        calendar.setTime(date);
 
        boolean useDateFormatSymbols = useDateFormatSymbols();
 
        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }
 
            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;
 
            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;
 
            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }

LocalDateTime使用介绍

时间初始化

//获取当前时间
LocalDateTime nowTime= LocalDateTime.now();
System.out.println("现在时间"+nowTime);
//自定义时间 of(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond)
LocalDateTime endTime = LocalDateTime.of(2020, 5, 20, 5, 20, 10,00);
System.out.println("设定时间"+endTime);

时间比较

```java
//比较   现在的时间 比 设定的时间 之前  返回的类型是Boolean类型
boolean isBefore = nowTime.isBefore(endTime);
System.out.println("现在的时间 比 设定的时间 之前"+isBefore);
//比较   现在的时间 和 设定的时候  相等  返回类型是Boolean类型
boolean euqal =nowTime.equals(endTime);
System.out.println("现在的时间 和 设定的时候 相等"+euqal);
//比较  现在的时间 比 设定的时间 之后  返回的类型是Boolean类型
boolean isAfter = nowTime.isAfter(endTime);
System.out.println("现在的时间 比 设定的时间 之后"+isAfter);

时间获取


// 获取当前时间
int year = nowTime.getYear();
int monthValue = nowTime.getMonthValue();
int dayofMonth = nowTime.getDayOfMonth();
int hour = nowTime.getHour();
int minute = nowTime.getMinute();
int second = nowTime.getSecond();
System.out.println("获得时间:" + year + "年" +monthValue+"月"+dayofMonth+"日" + hour+"时"+minute+"分"+second+"秒");// 打印当前时间的
DayOfWeek dayofWeek = nowTime.getDayOfWeek();//获取星期几
System.out.println("获得星期:"+dayofWeek);
int dayofYear = nowTime.getDayOfYear();//获取当前日子为年的第几天
System.out.println("全年:"+dayofYear+"天");

时间操作


```java
// 获取一年之前.minusYears(1) 这个 1 代表一年之前,如果是2就是两年之前
LocalDateTime minusYears = nowTime.minusYears(1);
System.out.println(minusYears);
LocalDateTime plusYears = nowTime.plusYears(1);//一年之后
System.out.println(plusYears);
LocalDateTime minusMonths = nowTime.minusMonths(1);//一个月前
System.out.println(minusMonths);
LocalDateTime plusMonths = nowTime.plusMonths(1);//一个月后
System.out.println(plusMonths);
LocalDateTime BeforeWeek = nowTime.minusWeeks(1);//一个星期前
System.out.println(BeforeWeek);
LocalDateTime AfterWeek = nowTime.plusWeeks(1);//一个星期后
System.out.println(AfterWeek);
LocalDateTime minusDays = nowTime.minusDays(1);//一天前
System.out.println(minusDays);
LocalDateTime plusDays = nowTime.plusDays(1);//一天后
System.out.println(plusDays);
LocalDateTime minusHours = nowTime.minusHours(1);//一个小时前
System.out.println(minusHours);
LocalDateTime plusHours = nowTime.plusHours(1);//一个小时后
System.out.println(plusHours);
LocalDateTime minusMinutes = nowTime.minusMinutes(1);//一分钟前
System.out.println(minusMinutes);
LocalDateTime plusMinutes = nowTime.plusMinutes(1);//一分钟后
System.out.println(plusMinutes);
LocalDateTime minusSeconds = nowTime.minusSeconds(1);//一秒前
System.out.println(minusSeconds);
LocalDateTime plusSeconds = nowTime.plusSeconds(1);//一秒后
System.out.println(plusSeconds);
LocalDateTime minusTime = nowTime.minus(23, ChronoUnit.MONTHS);//当前时间减少23个月
System.out.println(minusTime);

获得特殊时间

//根据需求需要取得当天的零点
LocalDateTime today_start = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);//当天零点
System.out.println(today_start);
LocalDateTime today_end = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);//获取当天结束时间
System.out.println(today_end);

LocalDateTime类型转换

 /**
     * LocalDate -> Date
     */
    public static Date asDate(LocalDate localDate) {
        return Date.from(localDate.atStartOfDay().atZone(ZoneId.of("GMT+08:00")).toInstant());
    }

    /**
     * Date -> LocalDate
     */
    public static LocalDate asLocalDate(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.of("GMT+08:00")).toLocalDate();
    }

    /**
     * Date -> LocalDateTime
     */
    public static LocalDateTime asLocalDateTime(Date date) {
        return Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.of("GMT+08:00")).toLocalDateTime();
    }
    **注意:ZoneId.systemDefault():用于返回系统默认时区
    	  ZoneId.of("GMT+08:00"):用于返回北京时区
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值