DateUtils.java 12.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
package org.nafmii.utils;


import org.nafmii.exception.JwtException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * Created by zhangzhenfang on 2018/5/16.
 */
public class DateUtils {

    public static String DATE_PATTERN ="yyyy-MM-dd HH:mm:ss";
    public static String SHORT_DATE_PATTERN ="yyyy-MM-dd";
    public static String format(Date date){
        DateFormat df=new SimpleDateFormat(DATE_PATTERN);
        return df.format(date);
    }
    public static String formatShortDate(Date date){
        DateFormat df=new SimpleDateFormat(SHORT_DATE_PATTERN);
        return df.format(date);
    }

    /**
     * 返回yyyy-MM-dd格式字符串时间
     * @Author Lifp
     * @Date 12:48 2020.9.16
     * @Param [date]
     * @return java.lang.String
     **/
    public static String formatShortDateStr(String date){
        if (date.contains(" ") || date.contains(":")) {
            date = date.substring(0, date.lastIndexOf("-") + 3);
        }
        return date;
    }

    public static String formatDate(Date date){
        DateFormat df=new SimpleDateFormat(DATE_PATTERN);
        return df.format(date);
    }

    public static Date nowDate() {
        return new Date();
    }

    public static Date  getDayBegin(Date date){
        if(date==null){
            return null;
        }
        Date todayBegin = org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DATE);
        return todayBegin;
    }

    /**
     * 指定日期的结束时间即第二天开始时间(条件查询应 date >= dayStart && date<dayEnd)
     * @param date
     * @return
     */
    public static Date getDayEnd(Date date){
        if(date==null){
            return null;
        }
        Date todayBegin = org.apache.commons.lang3.time.DateUtils.truncate(date, Calendar.DATE);
        return org.apache.commons.lang3.time.DateUtils.addDays(todayBegin,1);
    }

    public static String toDateString(Date date, String formatStr) {
        DateFormat df = getDateFormat(formatStr);
        return df.format(date);
    }

    /**
     * 获取DateFormat
     *
     * @param formatStr
     * @return
     */
    public static DateFormat getDateFormat(String formatStr) {
        DateFormat df = dateFormatMap.get(formatStr);
        if (df == null) {
            df = new SimpleDateFormat(formatStr);
            dateFormatMap.put(formatStr, df);
        }
        return df;
    }
    /**
     * DateFormat缓存
     */
    private static Map<String, DateFormat> dateFormatMap = new HashMap<>();

    /**
     * 将时间字符串转为LocalDateTime 格式
     */
    public static LocalDateTime strToLocalDate(String timeStr) {
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
        return LocalDateTime.parse(timeStr, fmt);
    }


    public static Date parseDate(String dateStr){
        if(dateStr== null){
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, DATE_PATTERN);
        } catch (ParseException e) {
            throw new JwtException("date format error",e);
        }
    }
    public static Date parseShortDate(String dateStr){
        if(dateStr== null){
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, SHORT_DATE_PATTERN);
        } catch (ParseException e) {
            throw new JwtException("date format error",e);
        }
    }
    public static Date parseDate(String dateStr,String... datePattern){
        if(dateStr== null){
            return null;
        }
        try {
            return org.apache.commons.lang3.time.DateUtils.parseDate(dateStr, datePattern);
        } catch (ParseException e) {
            throw new JwtException("date format error",e);
        }
    }

    // 判断两个日期是否为同一天
    public static boolean isSameDay(Date date1, Date date2) {
        if(date1 != null && date2 != null) {
            Calendar cal1 = Calendar.getInstance();
            cal1.setTime(date1);
            Calendar cal2 = Calendar.getInstance();
            cal2.setTime(date2);
            return isSameDay(cal1, cal2);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

    // 判断两个日期是否为同一天
    public static boolean isSameDay(Calendar cal1, Calendar cal2) {
        if(cal1 != null && cal2 != null) {
            return cal1.get(0) == cal2.get(0) && cal1.get(1) == cal2.get(1) && cal1.get(6) == cal2.get(6);
        } else {
            throw new IllegalArgumentException("The date must not be null");
        }
    }

    // 判断给定的两个日期相差天数
    public static int differentDays(Date date1,Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) {       //不同年
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0) {   //闰年
                    timeDistance += 366;
                }
                else    //不是闰年
                {
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else    //同年
        {
            System.out.println("判断day2 - day1 : " + (day2-day1));
            return day2-day1;
        }
    }

    // 判断给定的日期是否为一个月的第一天
    public static boolean isFirstDayOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        System.out.println(calendar.get(Calendar.MONTH)+1);
        return calendar.get(Calendar.DAY_OF_MONTH) == 1;
    }

    // 获取昨天的日期
    public static Date getYesterdayStr(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();
//        return getDayBegin(time);
        return time;
    }

    // 获取时间段内的所有日期
    public static List<Date> getRangeDate(Date start, Date end) {
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(start);
        min.set(Calendar.HOUR_OF_DAY, 0);
        min.set(Calendar.MINUTE, 0);
        min.set(Calendar.SECOND, 0);
        min.set(Calendar.MILLISECOND, 0);
        max.setTime(end);
        max.set(Calendar.HOUR_OF_DAY, -24);
        max.set(Calendar.MINUTE, 0);
        max.set(Calendar.SECOND, 0);
        max.set(Calendar.MILLISECOND, 0);
        List<Date> dateArrayList = new ArrayList<>();
        Calendar current = min;
        while (current.before(max) || current.equals(max)) {
            dateArrayList.add(current.getTime());
            current.add(Calendar.DAY_OF_MONTH, 1);
        }
        return dateArrayList;
    }

    /**
     * zjh
     * 返回日时分秒(重构)
     * @param
     * @return
     */
    public static String secondToTime(Date endIsTopTime) {
        long second =endIsTopTime.getTime()-System.currentTimeMillis();
        if (second < 0) {
            return "00:00:00";
        }
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        long hour = second % nd / nh;     //获取相差的小时数
        long min = second % nd % nh / nm;  //获取相差的分钟数
        long day = second / nd;
        long secondResult = (second % (1000 * 60)) / 1000;
        if (0 < day){
            return day + "天 "+hour+":"+min+":"+secondResult;
        }else {
            return hour+":"+min+":"+secondResult;
        }
    }

    /**
     * 获取30天之前的日期 yyyy-mm-hh 格式
     * @return
     */
    public static String recentMonthDateStr() {
        Date startDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), -30);
        return DateUtils.formatShortDate(startDate);
    }

    /**
     * 获取指定时间后一天的日期 yyyy-mm-hh 格式
     * @return
     */
    public static String getAfterDayStr(Date date) {
        Date startDate = DateUtils.getDayEnd(date);
        return DateUtils.formatShortDate(startDate);
    }

    /**
     * 获取指定时间段的日期
     * @return
     */
    public static Date getSpecifyTime(String hour, String minute) {
        Calendar time = Calendar.getInstance();
        time.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour));
        time.set(Calendar.MINUTE, Integer.parseInt(minute));
        time.set(Calendar.SECOND, 0);
//        time.set(Calendar.MILLISECOND, 999);
        return time.getTime();
    }

    public static List<String> getBetweenDate(String begin,String end){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<String> betweenList = new ArrayList<String>();
        try{
            Calendar startDay = Calendar.getInstance();
            startDay.setTime(format.parse(begin));
            startDay.add(Calendar.DATE, -1);

            while(true){
                startDay.add(Calendar.DATE, 1);
                Date newDate = startDay.getTime();
                String newend=format.format(newDate);
                betweenList.add(newend);
                if(end.equals(newend)){
                    break;
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return betweenList;
    }

    /**
     * 根据当前日期获得所在周的日期区间(周一和周日日期)
     * @Author Lifp
     * @Date 14:54 2020.9.17
     * @Param [date, whichDay(0-周一; 1-周日)]
     * @return java.lang.String
     **/
    public static String getTimeInterval(Date date, Integer whichDay) {
        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);
        // 返回结果
        String timeRsp;
        // 获得当前日期是一个星期的第几天
        int day = cal.get(Calendar.DAY_OF_WEEK);
        int cDate = Calendar.DATE;
        // 获取周1日期
        if (whichDay == 0) {
            int firstDayOfWeek = cal.getFirstDayOfWeek();
            // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值
            cal.add(cDate, cal.getFirstDayOfWeek() - day);
            timeRsp = formatShortDate(cal.getTime());
        } else if (whichDay == 1) {
            // 获取周日日期
            cal.add(cDate, 8-day);
            timeRsp = formatShortDate(cal.getTime());
        } else {
            return "";
        }
        return timeRsp;
    }

    /**
     * 获取19xx,20xx形式的年
     *
     * @param d
     * @return
     */
    public static int getYear(Date d) {
        Calendar now = Calendar.getInstance(TimeZone.getDefault());
        now.setTime(d);
        return now.get(Calendar.YEAR);
    }

    /**
     * 获取某年到现在的所有年份
     * @Author Lifp
     * @Date 16:43 2020.9.17
     * @Param [startYear]
     * @return java.util.List<java.lang.String>
     **/
    public static List<String> getYears(int startYear) {
        List<String> years = new ArrayList<>();
        int endYear = getYear(new Date());
        int local = endYear - startYear;
        while (local > -1) {
            years.add(String.valueOf(startYear++));
            local--;
        }
        return years;
    }

    /**
     * 返回手机号码
     */
    public static int getNum(int start,int end) {
        return (int)(Math.random()*(end-start+1)+start);
    }

    private static String[] telFirst="134,135,136,137,138,139,150,151,152,157,158,159,130,131,132,155,156,133,153".split(",");
    private static String getTel() {
        int index=getNum(0,telFirst.length-1);
        String first=telFirst[index];
        String second=String.valueOf(getNum(1,888)+10000).substring(1);
        String third=String.valueOf(getNum(1,9100)+10000).substring(1);
        return first+second+third;
    }




    public static void main(String[] args){
        Date date = parseShortDate("2020-09-20");
        System.out.println(getTimeInterval(date, 0));
        System.out.println(getTimeInterval(date, 1));
        System.out.println(getYear(new Date()));


    }

}