JAVA一些常用的时间操作

项目中经常有对时间进行处理的需求,下面是一些常用的操作整理,方便以后再次使用以及做相关复习。

1.字符串转换为日期

复制代码
 1  /**
 2      * 字符串转换为日期
 3      * @param dateStr 需要转换的日期
 4      * @param dateFormat 日期格式yyyy-MM-dd/yyyy-MM-dd HH:mm:ss
 5      */
 6     public static Date toDate(String dateStr, SimpleDateFormat dateFormat) throws ParseException{
 7         Date date = null;
 8         try {
 9             date = dateFormat.parse(dateStr);
10         } catch (ParseException e) {
11             logger.debug("Fail to convert String to Date, {}", dateStr);
12         }
13         return date;
14     }
复制代码

 

2.时间戳转日期

复制代码
    /**
     * 时间戳转日期
     * @param date
     * @return
     */
    public static String dateToTime(long time, SimpleDateFormat dateFormat) throws ParseException{
         String data = null;
         try {
             dateFormat.format(new Date(time*1000));    
         } catch (Exception e) {
             logger.debug("Fail to convert long to Date, {}", time);
         }
         return data;
    }
复制代码

 

3.日期格式化成字符串

复制代码
    /**
     * 日期格式化成字符串
     * @param date
     * @param dateFormat
     * @return
     * @throws ParseException
     */
    public static String toString(Date date, SimpleDateFormat dateFormat) throws ParseException{
        return dateFormat.format(date);
    }
复制代码

 

4.获取指定日期之前或之后的日期 ,十分秒为00:00:00

复制代码
    /**
     * 获取指定日期之前或之后的日期
     * @param date 
     * @param num 正数为之后,负数为之前
     * @return yyyy-MM-dd 00:00:00
     */
    public static Date getSpecificDate(Date date, int num){
        Calendar todayCal = Calendar.getInstance();
        todayCal.setTime(date);

        Calendar c = Calendar.getInstance();
        c.set(todayCal.get(Calendar.YEAR), todayCal.get(Calendar.MONTH), todayCal.get(Calendar.DAY_OF_MONTH) + num, 0, 0, 0);
        return c.getTime();
    }
复制代码

 

5.获取指定日期之前或之后的日期 ,时分秒为当前的

复制代码
    /**
     * 获取指定日期之前或之后的日期
     * @param date 
     * @param num 正数为之前,负数为之后
     * @return yyyy-MM-dd + 当前的时分秒
     */
    public static Date getSpecificDateAndHhMmSs(Date date,int num){
        Calendar c = Calendar.getInstance(); 
        c.setTime(date); 
        int day=c.get(Calendar.DATE); 
        c.set(Calendar.DATE,day - num); 
        return c.getTime(); 
    }
复制代码

 

6.将time类型的时间字符串 转换成 时、分

复制代码
    /**
     * 将time类型的时间字符串 转换成 时、分
     * HH-mm-ss -->>  HH-mm
     * @param time 
     * @return
     */
    public static String timeToHHMM(String time){
        return time.substring(0, time.length() - 3);
    }
复制代码

 

7.获取某个日期的时、分

复制代码
    /**
     * 获取某个日期的时、分
     * @param date
     * @return HH-mm
     */
    public static String getHM(Date date){
        Calendar ca = Calendar.getInstance(); 
        ca.setTime(date);
        Integer hour = ca.get(Calendar.HOUR_OF_DAY);//小时 
        Integer minute = ca.get(Calendar.MINUTE);//
        String rs_hour = hour.toString();
        String rs_minute = minute.toString();

        if (rs_hour.length() == 1){
            rs_hour = "0" + hour;
        }
        if(rs_minute.length() == 1){
            rs_minute = "0" + minute;
        }

        return rs_hour + ":" + rs_minute;
    }
复制代码

 

8.time类型的时间字符串 -->> 零点开始的秒数

复制代码
    /**
     * time类型的时间字符串 -->> 零点开始的秒数
     * @param time HH-mm / HH-mm-ss
     * @return
     */
    public static Integer timeToSeconds(String time){
          String[] timeSplit = null;
          int hours = 0,minutes = 0,seconds = 0;
          try {
              timeSplit = time.split(":");
              if (timeSplit.length == 2) {
                  hours = Integer.valueOf(timeSplit[0])*60*60;
                  minutes = Integer.valueOf(timeSplit[1])*60;
              }else if(timeSplit.length == 3){
                  hours = Integer.valueOf(timeSplit[0])*60*60;
                  minutes = Integer.valueOf(timeSplit[1])*60;
                  seconds = Integer.valueOf(timeSplit[2]);
              }else{
                  logger.debug("Fail to convert the time, {}", time);
              }
          } catch (Exception e) {
              logger.debug("Fail to convert the time, {}", time);
              throw e;
          }

        return hours + minutes + seconds;
    }
复制代码

 

9.零点开始的秒数转时间 -->> HH-mm-ss

复制代码
    /**
     * 零点开始的秒数转时间 -->> HH-mm-ss
     * @param durationSeconds
     * @return
     */
    public static String getDuration(int durationSeconds){  
        int hours = durationSeconds /(60*60);  
        int leftSeconds = durationSeconds % (60*60);  
        int minutes = leftSeconds / 60;  
        int seconds = leftSeconds % 60;  

        StringBuffer sBuffer = new StringBuffer();  
        sBuffer.append(addZeroPrefix(hours));  
        sBuffer.append(":");  
        sBuffer.append(addZeroPrefix(minutes));  
        sBuffer.append(":");  
        sBuffer.append(addZeroPrefix(seconds));  

        return sBuffer.toString();  
    }  

    public static String addZeroPrefix(int number){  
        if(number < 10)  
            return "0"+number;  
        else 
            return ""+number;  
    }
复制代码

 

10.比较两个日期相差的秒数

复制代码
    /**
     * 比较两个日期相差的秒数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getTimeSeconds(Date startDate,Date endDate) {
          long a = endDate.getTime();
          long b = startDate.getTime();
          return (int)((a - b) / 1000);
    }
复制代码

 

11.判断两个时间段是否存在交集

复制代码
    /**
     * 比较两个日期相差的秒数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getTimeSeconds(Date startDate,Date endDate) {
          long a = endDate.getTime();
          long b = startDate.getTime();
          return (int)((a - b) / 1000);
    }
复制代码

 

12.获取指定日期是星期几(1-7分别代表周一至周日)

复制代码
    /**
     * 获取指定日期是星期几(1-7分别代表周一至周日)
     * @return
     */
    public static int DayOfWeek(Date date){
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        boolean isFirstDay = (now.getFirstDayOfWeek() == Calendar.SUNDAY);
        int weekday = now.get(Calendar.DAY_OF_WEEK);
        if(isFirstDay){
            weekday = weekday - 1;
            if(weekday == 0){
                weekday = 7;
            }
        }
        return weekday;
    }
复制代码

 

posted @   微人类  阅读(485)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示