Java操作时间工具类


1 LocalDate快速入门

从Java 8之后,Java里面添加了许多的新特性,其中一个最常见也是最实用的便是日期处理的类——LocalDate。

新增的日期jar主要有三种:

java.time.LocalDate ->只对年月日做出处理

java.time.LocalTime ->只对时分秒纳秒做出处理

java.time.LocalDateTime ->同时可以处理年月日和时分秒

		// 获取今天的日期
		LocalDate today = LocalDate.now();
		// 今天是几号
		int dayofMonth = today.getDayOfMonth();
		// 今天是周几(返回的是个枚举类型,需要再getValue())
		int dayofWeek = today.getDayOfWeek().getValue();
		// 今年是哪一年
		int dayofYear = today.getDayOfYear();
		
		// 根据字符串取:
		LocalDate endOfFeb = LocalDate.parse("2018-02-28"); 
		// 严格按照yyyy-MM-dd验证,02写成2都不行,当然也有一个重载方法允许自己定义格式

常用方法简介:
img

img

img

img

2 判断time是否在now的n天之内

   /**
     * 判断time是否在now的n天之内
     * @param time
     * @param now
     * @param n 正数表示在条件时间n天之后,负数表示在条件时间n天之前
     * @return
     */
    public static boolean belongDate(Date time, Date now, int n) {
    
    
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.setTime(now);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, n);
        Date before7days = calendar.getTime(); //得到n前的时间
        if (before7days.getTime() < time.getTime()) {
    
    
            return true;
        } else {
    
    
            return false;
        }
    }

3 判断某个时间是否是在条件的起始时间与结束时间之内

    /**
     * 判断time是否在from,to之内
     *
     * @param time 指定日期
     * @param from 开始日期
     * @param to 结束日期
     * @return
     */
    public static boolean belongCalendar(Date time, Date from, Date to) {
    
    
        Calendar date = Calendar.getInstance();
        date.setTime(time);
        Calendar after = Calendar.getInstance();
        after.setTime(from);
        Calendar before = Calendar.getInstance();
        before.setTime(to);
        if (date.after(after) && date.before(before)) {
    
    
            return true;
        } else {
    
    
            return false;
        }
    }

4 判断给定时间与当前时间相差多少天

   public static long getDistanceDays(String date) {
    
    
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long days = 0;
        try {
    
    
            Date time = df.parse(date);//String转Date
            Date now = new Date();//获取当前时间
            long time1 = time.getTime();
            long time2 = now.getTime();
            long diff = time1 - time2;
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
        return days;//正数表示在当前时间之后,负数表示在当前时间之前
    }

或者用更为简洁的方法:

在项目中,经常需要比较两个日期之间相差几天,或者相隔几个月,我们可以使用java8的Period来进行处理。

    LocalDate today = LocalDate.now();
    LocalDate specifyDate = LocalDate.of(2015, 10, 2);
    Period period = Period.between(specifyDate, today);
    System.out.println(period.getDays()); 
    //4
    System.out.println(period.getMonths()); 
    //1
    System.out.println(specifyDate.until(today, ChronoUnit.DAYS)); 
    //401
    // 输出结果41401

5 将String转换成Date

    private static final String LONG_PATTERN="yyyy-MM-dd HH:mm:ss";
    private static final String SHORT_PATTERN="yyyy-MM-dd";
    /**
     * 将字符串转为日期
     */
    public static Date parseStringToDate(String str, String pattern){
    
    
        DateFormat df = null;
        if( pattern!=null && !"".equals(pattern) ){
    
    
            df=new SimpleDateFormat( pattern );
        }else{
    
    
            df=new SimpleDateFormat( LONG_PATTERN );
        }
        Date d=null;
        try {
    
    
            d=df.parse(str);
        } catch (ParseException e) {
    
    
            e.printStackTrace();
        }
        return d;
    }

或者:

在java8之前,我们进行时间格式化主要是使用SimpleDateFormat,而在java8中,主要是使用DateTimeFormatter,java8中,预定义了一些标准的时间格式,我们可以直接将时间转换为标准的时间格式:

    String specifyDate = "20151011";
    DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
    LocalDate formatted = LocalDate.parse(specifyDate,formatter); 
    System.out.println(formatted); 
    //输出2015-10-11

当然,很多时间标准的时间格式可能也不满足我们的要求,我们需要转为自定义的时间格式

    DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("YYYY MM dd");
    System.out.println(formatter2.format(LocalDate.now()));
    //结果2015 10 11

6 Date与LocalDateTime互转

   //将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
    public static LocalDateTime dateConvertToLocalDateTime(Date date) {
    
    
        return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }
    //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
    public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
    
    
        return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
    }

7 日期前后比较

比较2个日期哪个在前,哪个在后,java8 LocalDate提供了2个方法,isAfter()是否在之前,isBefore

    LocalDate today = LocalDate.now();
    LocalDate specifyDate = LocalDate.of(2015, 10, 20);
    System.out.println(today.isAfter(specifyDate));
//true

猜你喜欢

转载自blog.csdn.net/ZGL_cyy/article/details/121329462