zoukankan      html  css  js  c++  java
  • java关于时间比较|String转Date|Date转String|指定时间加上指定天数后的日期|当时时间加上指定天数后的日期等的方法

    目录

    1、比较前后两个时间,相差几年或几月或几日

    2、比较前后两个时间是否在同月

    3、获取当前系统时间

    4、日期转换成字符串

    5、期转换成字符串  包含时分秒

    6、字符串转换成日期

    7、字符串转换成日期 包含时分秒

    8、指定时间加上指定天数后的日期:

    9、当时时间加上指定天数后的日期

    10、当前时间-传过来的时间,两者相差几分钟

    11、获取上周周一时间

    12、获取本周周一时间

    13、获取下周周一时间

                      14、获取上个月的时间


     


    在网上有很多这类关于时间的比较,

    但是都比较杂,看着很累,我呢就提取了一些精华的部分和经常用到的一些时间比较,其中包括

    1、比较前后两个时间,相差几年或几月或几日

    例如2018-02-12  到2018-03-10,相差0个月

    2018-02-09到2018-03-10,相差1个月

    2、比较前后两个时间是否在同月

    例如2018-02-12  和 2018-03-10,不是在同一个月

    3、获取当前系统时间

    4、日期转换成字符串

    5、期转换成字符串  包含时分秒

    6、字符串转换成日期

    7、字符串转换成日期 包含时分秒

    代码如下:

    public class CompareDate {
    
    
        public static void main(String[] args) throws Exception{
    //        int i = compareMonth("2018-03-01", null);
            int i = CompareDate.compareDate("2017-02-13", null, 1);
            System.out.println(i);
        }
    
    
        /**
         * 比较前后两个时间,相差几年或几月或几日
         * @param date1 需要比较的时间 不能为空(null),需要正确的日期格式
         * @param date2 被比较的时间  为空(null)则为当前时间
         * @param stype 返回值类型   0为多少天,1为多少个月,2为多少年
         * @return
         */
        public static int compareDate(String date1,String date2,int stype){
            int n = 0;
    
            String[] u = {"天","月","年"};
            String formatStyle = stype==1?"yyyy-MM-dd":"yyyy-MM-dd";
    
            date2 = date2==null?CompareDate.getCurrentDate():date2;
    
            DateFormat df = new SimpleDateFormat(formatStyle);
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            try {
                c1.setTime(df.parse(date1));
                c2.setTime(df.parse(date2));
            } catch (Exception e3) {
                System.out.println("比较时间异常");
            }
            //List list = new ArrayList();
            while (!c1.after(c2)) {                     // 循环对比,直到相等,n 就是所要的结果
                //list.add(df.format(c1.getTime()));    // 这里可以把间隔的日期存到数组中 打印出来
                n++;
                if(stype==1){
                    c1.add(Calendar.MONTH, 1);          // 比较月份,月份+1
                }
                else{
                    c1.add(Calendar.DATE, 1);           // 比较天数,日期+1
                }
            }
    
            n = n-1;
    
            if(stype==2){
                n = (int)n/365;
            }
    
            System.out.println(date1+" -- "+date2+" 相差多少"+u[stype]+":"+n);
            return n;
        }
    
    
        /**
         * 比较前后两个时间是否在同月
         * @param beginTime
         * @param endTime
         * @return
         */
        public static int compareMonth(String beginTime,String endTime){
           endTime=(endTime==null?CompareDate.getCurrentDate():endTime);
            System.out.println(endTime);
    
            //将String转为Date
            Date beginDate = CompareDate.StrToDate(beginTime);
            Date endDate = CompareDate.StrToDate(endTime);
    
            //获取前者中的月份
            Calendar beginCal = Calendar.getInstance();
            beginCal.setTime(beginDate);
            int beginMonth = beginCal.get(Calendar.MONTH)+1;
            //获取后者中的月份
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(endDate);
            int endMonth = endCal.get(Calendar.MONTH)+1;
    
            return endMonth-beginMonth;
        }
    
    
        /**
         * 得到当前日期
         * @return
         */
        public static String getCurrentDate() {
            Calendar c = Calendar.getInstance();
            Date date = c.getTime();
            SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
            return simple.format(date);
    
        }
    
        /**
         * 日期转换成字符串
         * @param date
         * @return str
         */
        public static String DateToStr(Date date) {
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String str = format.format(date);
            return str;
        }
    
        /**
         * 日期转换成字符串  包含时分秒
         * @param date
         * @return str
         */
        public static String DateToStrIncludeHMS(Date date) {
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = format.format(date);
            return str;
        }
    
        /**
         * 字符串转换成日期
         * @param str
         * @return
         */
        public static Date StrToDate(String str) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Date date = null;
            try {
                date = format.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
    
    
        /**
         * 字符串转换成日期 包含时分秒
         * @param str
         * @return date
         */
        public static Date StrToDateIncludeHMS(String str) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = null;
            try {
                date = format.parse(str);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
    }

    2019/11/11 新增

    8、指定时间加上指定天数后的日期:

    比如指定时间的7天后的日期,14天后的日期等

    9、当时时间加上指定天数后的日期

    比如当前时间的7天后的日期,14天后的日期等

    
    
    import net.sf.json.JSONObject;
    
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    /**
     * Created by yjl on 2019/11/11.
     */
    public class Util {
        
    
        /**
         * 指定日期加上天数后的日期
         * @param date 时间
         * @param pattern 时间格式化的格式 eg:yyyy-MM-dd HH:mm:ss
         * @param num 为增加的天数
         * @return
         */
        public static String getTimePlusDay(String date,String pattern,int num){
    
            String enddate="";
            try {
                //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat format = new SimpleDateFormat(pattern);
                Date currdate = format.parse(date);
                System.out.println("传入的日期是:" + currdate);
                Calendar ca = Calendar.getInstance();
                ca.setTime(currdate);
                ca.add(Calendar.DATE, num);// num为增加的天数,可以改变的
                currdate = ca.getTime();
                 enddate = format.format(currdate);
                System.out.println("增加天数以后的日期:" + enddate);
            }catch (Exception e){
                e.printStackTrace();
                enddate="时间格式化异常,请检查getTimePlusDay()方法";
            }
    
            return enddate;
        }
    
    
        //当前日期加上天数:
    
    
        /**
         * 当前日期加上天数后的日期
         * @param pattern 时间格式化的格式 eg:yyyy-MM-dd HH:mm:ss
         * @param num 为增加的天数
         * @return
         */
        public static String getCurrentTimePlusDay(String pattern,int num){
            Date d = new Date();
            //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            String currdate = format.format(d);
            System.out.println("现在的日期是:" + currdate);
    
            Calendar ca = Calendar.getInstance();
            ca.add(Calendar.DATE, num);// num为增加的天数,可以改变的
            d = ca.getTime();
            String enddate = format.format(d);
            System.out.println("增加天数以后的日期:" + enddate);
            return enddate;
        }
    
        public static void main(String[] args) {
            //测试用例
            getTimePlusDay("201910280000","yyyyMMddHHmm",14); //输出:增加天数以后的日期:201911110000
            getTimePlusDay("2019-10-28 00:00","yyyy-MM-dd HH:mm",14); //输出:增加天数以后的日期:2019-11-11 00:00
            getCurrentTimePlusDay("yyyyMMddHHmm",14); //输出:增加天数以后的日期:201911251936
            getCurrentTimePlusDay("yyyy-MM-dd HH:mm",14); //输出:增加天数以后的日期:2019-11-25 19:36
    
        }
    }
    

    2019/11/27 新增

    10、当前时间-传过来的时间,两者相差几分钟

    /**
         * 当前时间-传过来的时间,两者相差几分钟
         * @param dataStr
         * @return
         */
        public static Long compareDate(String dataStr){
            long diff=0L;
            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                long currentTime =System.currentTimeMillis();
                //从对象中拿到时间
                long createTime = df.parse(dataStr).getTime();
                diff=(currentTime-createTime)/1000/60;
                System.out.println("当前系统时间为:"+currentTime+",传过来的时间为:"+createTime+",两个时间差为:"+diff+"分钟");
    
            } catch (ParseException e) {
                e.printStackTrace();
                System.out.println("传过来比较的时间格式非yyyy-MM-dd HH:mm:ss格式:"+dataStr);
            }
    
            return diff;
        }
    
    
        public static void main(String[] args) {
            compareDate("2019-11-27 15:10:30"); //当前系统时间为:1574839173574,传过来的时间为:1574838630000,两个时间差为:9分钟
            compareDate("2019-11-27 15:30:30"); //当前系统时间为:1574839354676,传过来的时间为:1574839830000,两个时间差为:-7分钟
        }

    2019/11/28 新增

    11、获取上周周一时间

    12、获取本周周一时间

    13、获取下周周一时间

    /**
         * 获取上周周一
         * @param date
         * @return
         */
        public static Date getLastWeekMonday(Date date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(getThisWeekMonday(date));
            cal.add(Calendar.DATE, -7);
            return cal.getTime();
        }
    
    
    
        public static Date getThisWeekMonday(Date date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            // 获得当前日期是一个星期的第几天
            int dayWeek = cal.get(Calendar.DAY_OF_WEEK);
            if (1 == dayWeek) {
                cal.add(Calendar.DAY_OF_MONTH, -1);
            }
            // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一
            cal.setFirstDayOfWeek(Calendar.MONDAY);
            // 获得当前日期是一个星期的第几天
            int day = cal.get(Calendar.DAY_OF_WEEK);
            // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
            cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
            return cal.getTime();
        }
    
    
    
        public static Date getNextWeekMonday(Date date) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(getThisWeekMonday(date));
            cal.add(Calendar.DATE, 7);
            return cal.getTime();
        }
    
    
    public static void main(String[] args) {
           
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date date = new Date();
            String getLastWeekMonday = sdf.format(getLastWeekMonday(date)); 
            String getThisWeekMonday = sdf.format(getThisWeekMonday(date));
            String getNextWeekMonday = sdf.format(getNextWeekMonday(date));
            System.out.println("getLastWeekMonday:"+getLastWeekMonday); //getLastWeekMonday:20191118
            System.out.println("getThisWeekMonday:"+getThisWeekMonday); //getThisWeekMonday:20191125
            System.out.println("getNextWeekMonday:"+getNextWeekMonday); //getNextWeekMonday:20191202
        }

    2020/01/07 新增

    14、获取上个月的时间

    /**
         * 获取上个月的时间
         * @param formatStr 格式化格式
         * @return
         */
        public static String getLastMonth(String formatStr) {
            if (formatStr == null || "".equals(formatStr)){
                formatStr = "yyyy-MM";
            }
            SimpleDateFormat format = new SimpleDateFormat(formatStr);
            Date date = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date); // 设置为当前时间
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月
            date = calendar.getTime();
            String accDate = format.format(date);
            return accDate;
        }

    欢迎大家测试,提出更多关于时间比较的想法,然后大家一起补充

  • 相关阅读:
    [转]JavaScript和html5 canvas生成圆形印章
    [转]微信小程序开发:http请求
    [转]Clean up after Visual Studio
    [转]How to Clean the Global Assembly Cache
    [转].NET Core dotnet 命令大全
    [转].NET 4.5+项目迁移.NET Core的问题记录 HTTP Error 502.5
    [转]How do I run msbuild from the command line using Windows SDK 7.1?
    [转]glyphicons-halflings-regular字体 图标
    [转]程序集之GAC---Global Assembly Cache
    [转]How can I install the VS2017 version of msbuild on a build server without installing the IDE?
  • 原文地址:https://www.cnblogs.com/jalenFish/p/14099047.html
Copyright © 2011-2022 走看看