java 日期处理(日常使用归类~~~)

我们在项目开发过程中,需要后台处理各种各样的时间格式和对时间的处理!

接下来对常见的日期进行大概的分享~~

1.时间戳类

/** 
     * 时间戳转换成日期格式字符串 
     * @param seconds 精确到秒的字符串 
     * @param formatStr 为null时默认yyyy-MM-dd HH:mm:ss
     * @return 返回日期字符串
     */  
    public static String timeStamp2Date(String seconds,String format) {  
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){  
            return "";  
        }
        
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }   
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        //Date是精确到毫秒的13位时间戳,所以秒要*1000
        Date date = new Date(Long.valueOf(seconds+"000"));
        String dateString = sdf.format(date);
        return dateString;  
    }

    /** 
     * 日期格式字符串转换成时间戳 
     * @param date 字符串日期 
     * @param format 默认:yyyy-MM-dd HH:mm:ss 
     * @return 精确到秒的时间戳
     */
    public static String date2TimeStamp(String date_str,String format){  
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        try {  
            SimpleDateFormat sdf = new SimpleDateFormat(format);  
            return String.valueOf(sdf.parse(date_str).getTime()/1000);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return "";  
    }

    /** 
     * 取得当前时间戳(精确到秒) 
     * @return 
     */  
    public static String getNowTimeStamp(){  
        long time = System.currentTimeMillis();
        String timestamp = String.valueOf(time/1000);  
        return timestamp;  
    }

2.时间Date的方法和处理

 /**
    * 得到当前日期字符串.
    * @return String 日期字符串,例如2022-03-17
    * @since 1.0
    */
   public static String getDate() {
      return getDate(DateUtils.DATE_FORMAT);
   }

   /**
    * 得到当前时间字符串.
    * @return String 时间字符串,例如 09:51:53
    * @since 1.0
    */
   public static String getTime() {
      return formatDate(new Date(), DateUtils.TIME_FORMAT);
   }

   /**
    * 得到当前日期和时间字符串.
    * @return String 日期和时间字符串,例如 2022-03-17 09:51:53
    * @since 1.0
    */
   public static String getDateTime() {
      return formatDate(new Date(), DateUtils.DATETIME_FORMAT);
   }

   /**
    * 获取当前时间指定格式下的字符串.
    * @param pattern
    *            转化后时间展示的格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
    * @return String 格式转换之后的时间字符串.
    * @since 1.0
    */
   public static String getDate(String pattern) {
      return DateFormatUtils.format(new Date(), pattern);
   }

   /**
    * 获取指定日期的字符串格式.
    * @param date  需要格式化的时间,不能为空
    * @param pattern 时间格式,例如"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss"等
    * @return String 格式转换之后的时间字符串.
    * @since 1.0
    */
   public static String getDate(Date date, String pattern) {
      return DateFormatUtils.format(date, pattern);
   }

   /**
    * 获取日期时间字符串,默认格式为(yyyy-MM-dd).
    * @param date 需要转化的日期时间
    * @param pattern 时间格式,例如"yyyy-MM-dd" "HH:mm:ss" "E"等
    * @return String 格式转换后的时间字符串
    * @since 1.0
    */
   public static String formatDate(Date date, Object... pattern) {
      String formatDate = null;
      if (pattern != null && pattern.length > 0) {
         formatDate = DateFormatUtils.format(date, pattern[0].toString());
      } else {
         formatDate = DateFormatUtils.format(date, DateUtils.DATE_FORMAT);
      }
      return formatDate;
   }

   /**
    * 获取当前年份字符串.
    * @return String 当前年份字符串,例如 2022
    * @since 1.0
    */
   public static String getYear() {
      return formatDate(new Date(), "yyyy");
   }

   /**
    * 获取当前月份字符串.
    * @return String 当前月份字符串,例如 03
    * @since 1.0
    */
   public static String getMonth() {
      return formatDate(new Date(), "MM");
   }

   /**
    * 获取当前天数字符串.
    * @return String 当前天数字符串,例如 17
    * @since 1.0
    */
   public static String getDay() {
      return formatDate(new Date(), "dd");
   }

   /**
    * 获取当前星期字符串.
    * @return String 当前星期字符串,例如星期三
    * @since 1.0
    */
   public static String getWeek() {
      return formatDate(new Date(), "E");
   }

   /**
    * 将日期型字符串转换为日期格式.
    * 支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
    * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"
    * @param str
    * @return Date
    * @since 1.0
    */
   public static Date parseDate(Object str) {
      if (str == null) {
         return null;
      }
      try {
         return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
      } catch (ParseException e) {
         return null;
      }
   }
 /**
    * 获取当前日期与指定日期相隔的天数.
    * @param date 给定的日期
    * @return long 日期间隔天数,正数表示给定日期在当前日期之前,负数表示在当前日期之后
    * @since 1.0
    */
   public static long pastDays(Date date) {
      // 将指定日期转换为yyyy-MM-dd格式
      date = DateUtils.parseDate(DateUtils.formatDate(date, DateUtils.DATE_FORMAT));
      // 当前日期转换为yyyy-MM-dd格式
      Date currentDate = DateUtils.parseDate(DateUtils.formatDate(new Date(), DateUtils.DATE_FORMAT));
      long t=0;
      if(date!=null&&currentDate!=null){
         t = (currentDate.getTime() - date.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
      }
      return t;
   }

   /**
    * 获取当前日期指定天数之后的日期.
    * @param num   相隔天数
    * @return Date 日期
    * @since 1.0
    */
   public static Date nextDay(int num) {
      Calendar curr = Calendar.getInstance();
      curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH) + num);
      return curr.getTime();
   }
/**
    * 计算两个日期之间相差天数.
    * @param start     计算开始日期
    * @param end       计算结束日期
    * @return long 相隔天数
    * @since 1.0
    */
   public static long getDaysBetween(Date start, Date end) {
      // 将指定日期转换为yyyy-MM-dd格式
      start = DateUtils.parseDate(DateUtils.formatDate(start, DateUtils.DATE_FORMAT));
      // 当前日期转换为yyyy-MM-dd格式
      end = DateUtils.parseDate(DateUtils.formatDate(end, DateUtils.DATE_FORMAT));

      long diff=0;
      if(start!=null&&end!=null) {
         diff = (end.getTime() - start.getTime()) / DateUtils.MILLISECONDS_PER_DAY;
      }
      return diff;
   }

   /**
    * 计算两个日期之前相隔多少周.
    * @param start      计算开始时间
    * @param end    计算结束时间
    * @return long 相隔周数,向下取整
    * @since 1.0
    */
   public static long getWeeksBetween(Date start, Date end) {
      return getDaysBetween(start, end) / DateUtils.DAYS_PER_WEEK;
   }

   /**
    * 获取与指定日期间隔给定天数的日期.
    * @param specifiedDay    给定的字符串格式日期,支持的日期字符串格式包括"yyyy-MM-dd","yyyy-MM-dd HH:mm:ss",
    *            "yyyy-MM-dd HH:mm", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss",
    *            "yyyy/MM/dd HH:mm"
    * @param num   间隔天数
    * @return String 间隔指定天数之后的日期
    * @since 1.0
    */
   public static String getSpecifiedDayAfter(String specifiedDay, int num) {
      Date specifiedDate = parseDate(specifiedDay);
      Calendar c = Calendar.getInstance();
      c.setTime(specifiedDate);
      int day = c.get(Calendar.DATE);
      c.set(Calendar.DATE, day + num);
      String dayAfter = formatDate(c.getTime(), DateUtils.DATE_FORMAT);
      return dayAfter;
   }

   /**
    * 计算两个日期之前间隔的小时数.
    * 
    * @param date1
    *            结束时间
    * @param date2
    *            开始时间
    * @return String 相差的小时数,保留一位小数
    * @since 1.0
    */
   public static String dateMinus(Date date1, Date date2) {
      if (date1 == null || date2 == null) {
         return "0";
      }
      Long r = date1.getTime() - date2.getTime();
      DecimalFormat df = new DecimalFormat("#.0");
      double result = r * 1.0 / DateUtils.MILLISECONDS_PER_HOUR;
      return df.format(result);
   }

   /**
    * 获取当前季度 .
    * 
    * @return Integer 当前季度数
    * @since 1.0
    */
   public static Integer getCurrentSeason() {
      Calendar calendar = Calendar.getInstance();
      Integer month = calendar.get(Calendar.MONTH) + 1;
      int season = 0;
      if (month >= 1 && month <= 3) {
         season = 1;
      } else if (month >= 4 && month <= 6) {
         season = 2;
      } else if (month >= 7 && month <= 9) {
         season = 3;
      } else if (month >= 10 && month <= 12) {
         season = 4;
      }
      return season;
   }

3.Calendar 类常用方法

获取时间

 // 使用默认时区和语言环境获得一个日历
    Calendar cal = Calendar.getInstance();
    // 赋值时年月日时分秒常用的6个值,注意月份下标从0开始,所以取月份要+1
    System.out.println("年:" + cal.get(Calendar.YEAR));
    System.out.println("月:" + (cal.get(Calendar.MONTH) + 1));       
    System.out.println("日:" + cal.get(Calendar.DAY_OF_MONTH));
    System.out.println("时:" + cal.get(Calendar.HOUR_OF_DAY));
    System.out.println("分:" + cal.get(Calendar.MINUTE));
    System.out.println("秒:" + cal.get(Calendar.SECOND));

今天是2022年3月17日。看看结果:

年:2022
月:3
日:17
时:14
分:23
秒:25

set方法:

        将已知的日历字段设置为给定值。

Calendar c = Calendar.getInstance();
       //设置月份,设置10月份。月份是以0开始计数
        c.set(Calendar.MONTH, 6);
        //设置年,月,日
        c.set(2025, 10, 1);

add方法:

        在此基础整体便宜(正数向前推移;负数向后)

Calendar c = Calendar.getInstance();
//修改年份,减1年
 c.add(Calendar.YEAR, -1);
 //此处是获取到当月天数后,会在当前月份基础上腿100天)
 c.add(Calendar.DAY_OF_MONTH, -100);

getTime方法:

  把日历对象转换成Date日期对象。

  Calendar c = Calendar.getInstance();
  Date date = c.getTime();

以上!就是时间的一些处理方法和获取方法,具体如何使用,看业务情况!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

一枝风

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

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

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

打赏作者

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

抵扣说明:

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

余额充值