Java常用的工具类之时间类

1. 时间类的工具类

1.1 获取当前类型的yyyyMMddHHmmss格式字符串
   public static String getCurrentTime24() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");//也可以是yyyyMMddHHmmssSSS
        return simpleDateFormat.format(new Date());
    }
1.2 比较两个字符串时间大小
     public static long calcTwoTimesDiff(String largeTime, String smallTime) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date largeTimeD = df.parse(largeTime);
        Date smallTimeD = df.parse(smallTime);
        long twoTimesDiff = largeTimeD.getTime() - smallTimeD.getTime();
        return twoTimesDiff;
    }
1.3 获取前一天日期
    public static String getLastdayOfTheDay(String settDate) throws Exception {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d = df.parse(settDate + "000000");
        c.setTime(d);
        c.set(5, c.get(5) - 1);
        d = c.getTime();
        return df.format(d).substring(0, 8);
    }
1.4 获取明天的日期
   public static String getNextdayOfTheDay(String settDate) throws Exception {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d = df.parse(settDate + "000000");
        c.setTime(d);
        c.set(5, c.get(5) + 1);
        d = c.getTime();
        return df.format(d).substring(0, 8);
    }
1.5 获取指定天数的日期
     public static String getSomeDayOfTheDay(String settDate, int somedays) throws Exception {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d = df.parse(settDate + "000000");
        c.setTime(d);
        c.set(5, c.get(5) + somedays);
        d = c.getTime();
        return df.format(d).substring(0, 8);
    }
1.6 获取某月最后一天
   public static String getFinalDayOfTheMoth(String day) throws Exception {
        Calendar c = Calendar.getInstance();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        Date d = df.parse(day + "000000");
        c.setTime(d);
        c.set(5, 1);
        c.roll(5, -1);
        d = c.getTime();
        return df.format(d).substring(0, 8);
    }

猜你喜欢

转载自blog.csdn.net/Charles_lxx/article/details/107766627
今日推荐