Java操作时间工具类


在这里插入图片描述

想学习架构师构建流程请跳转: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
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
package com.hexiang.utils; import java.text.SimpleDateFormat; import java.util.*; public class CalendarUtil { public static void main(String args[]) { System.out.println("First day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByWeek(new Date()))); System.out.println("Last day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByWeek(new Date()))); System.out.println("First day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByMonth(new Date()))); System.out.println("Last day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByMonth(new Date()))); } /** * 获得所在星期的第一天 */ public static Date getFirstDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 now.set(Calendar.DATE, first_day_of_week); return now.getTime(); } /** * 获得所在星期的最后一天 */ public static Date getLastDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 int last_day_of_week = first_day_of_week + 6; // 星期日 now.set(Calendar.DATE, last_day_of_week); return now.getTime(); } /** * 获得所在月份的最后一天 * @param 当前月份所在的时间 * @return 月份的最后一天 */ public static Date getLastDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.MONTH, now.get(Calendar.MONTH) + 1); now.set(Calendar.DATE, 1); now.set(Calendar.DATE, now.get(Calendar.DATE) - 1); now.set(Calendar.HOUR, 11); now.set(Calendar.MINUTE, 59); now.set(Calendar.SECOND, 59); return now.getTime(); } /** * 获得所在月份的第一天 * @param 当前月份所在的时间 * @return 月份的第一天 */ public static Date getFirstDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, 0); now.set(Calendar.HOUR, 12); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); return now.getTime(); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赵广陆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值