DateUtil.java 14.6 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 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
package cn.fw.valhalla.common.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

/**
 * 日期处理工具
 * <p>
 *
 * @author kurisu
 */
public final class DateUtil {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 默认构造器
     */
    private DateUtil() {
        throw new UnsupportedOperationException();
    }


    public static Date parse(String date) {
        try {
            return sdf.parse(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 开始日期处理
     */
    public static Date startDate(final Date date) {
        if (date == null) {
            return null;
        }
        return localDateTime2Date(date2LocalDate(date).atStartOfDay());
    }

    /**
     * 最结束日期处理
     */
    public static Date endDate(final Date date) {
        if (date == null) {
            return null;
        }
        return localDateTime2Date(date2LocalDate(date).plusDays(1).atStartOfDay());
    }

    /**
     * 处理日期,保留年月日
     */
    public static LocalDate date2LocalDate(final Date date) {
        if (date == null) {
            return null;
        }
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).toLocalDate();
    }

    public static LocalTime date2LocalTime(final Date date) {
        if (date == null) {
            return null;
        }
        return LocalTime.of(date.getHours(), date.getMinutes(), date.getSeconds());
    }

    public static LocalDateTime date2LocalDateTime(final Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }

    /**
     * convert LocalDateTime to Date
     */
    public static Date localDateTime2Date(final LocalDateTime dateTime) {
        return Date.from(dateTime.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * convert LocalDate to Date
     */
    public static Date localDate2Date(final LocalDate localDate) {
        if (localDate == null) {
            return null;
        }
        return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
    }

    public static Date getBeginInTime(Date inTime) {
        if (inTime == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        return c.getTime();
    }

    public static Date getEndInTime(Date inTime) {
        if (inTime == null) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    /**
     * 得到本周周一
     *
     * @return
     */
    public static Date getMondayOfThisWeek(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0) {
            day_of_week = 7;
        }
        c.add(Calendar.DATE, -day_of_week + 1);
        return c.getTime();
    }

    /**
     * 得到本周周日
     *
     * @return
     */
    public static Date getSundayOfThisWeek(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (day_of_week == 0) {
            day_of_week = 7;
        }
        c.add(Calendar.DATE, -day_of_week + 7);
        return c.getTime();
    }

    /**
     * 得到月初
     *
     * @return
     */
    public static Date getMonthFirstDay(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);
        return c.getTime();
    }

    /**
     * 获取当月月初时间
     */
    public static Date getMonthFirstDay() {
        return DateUtil.localDate2Date(LocalDateTime.now()
                .with(TemporalAdjusters.firstDayOfMonth()).toLocalDate());
    }

    /**
     * 得到月末
     *
     * @return
     */
    public static Date getMonthEndDay(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        c.add(Calendar.MONTH, 1);
        c.set(Calendar.DAY_OF_MONTH, 0);
        return c.getTime();
    }

    /**
     * 得到年初
     *
     * @return
     */
    public static Date getYearFirstDay(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        int x = c.get(Calendar.YEAR);
        try {
            return sdf.parse(x + "-01" + "-01");
        } catch (Exception e) {

        }
        return null;
    }

    /**
     * 得到年末
     *
     * @return
     */
    public static Date getYearEndDay(Date inTime) {
        Calendar c = Calendar.getInstance();
        c.setTime(inTime);
        int x = c.get(Calendar.YEAR);
        try {
            return sdf.parse(x + "-12" + "-31");
        } catch (Exception e) {

        }
        return null;
    }

    public static Date getThisHourStartTime(Date time) {
        final LocalDateTime thisHourStart = LocalDateTime.of(DateUtil.date2LocalDateTime(time).getYear(),
                DateUtil.date2LocalDateTime(time).getMonth(),
                DateUtil.date2LocalDateTime(time).getDayOfMonth(),
                DateUtil.date2LocalDateTime(time).getHour(),
                0, 0);
        return DateUtil.localDateTime2Date(thisHourStart);
    }

    public static Date getThisHourEndTime(Date time) {
        final LocalDateTime thisHourEnd = LocalDateTime.of(DateUtil.date2LocalDateTime(time).getYear(),
                DateUtil.date2LocalDateTime(time).getMonth(),
                DateUtil.date2LocalDateTime(time).getDayOfMonth(),
                DateUtil.date2LocalDateTime(time).getHour(),
                59, 59);
        return DateUtil.localDateTime2Date(thisHourEnd);
    }

    /**
     * 获取当天起始时间
     *
     * @return 当天起始时间
     */
    public static Date getCurrentDayStartTime() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime start = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 0, 0, 0);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = start.atZone(zone).toInstant();
        return Date.from(instant);
    }

    /**
     * 获取当天结束时间
     *
     * @return 当天结束时间
     */
    public static Date getCurrentDayEndTime() {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime end = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 23, 59, 59);
        ZoneId zone = ZoneId.systemDefault();
        Instant instant = end.atZone(zone).toInstant();
        return Date.from(instant);
    }


    /**
     * 获取短时间字符串
     *
     * @param date 需要转换格式的日期
     * @return 返回短时间字符串格式 yyyy-MM-dd
     */
    public static String getStringDateShort(Date date) {
        if (date == null) {
            return null;
        }
        String dateString = sdf.format(date);
        return dateString;
    }

    /**
     * 获取时间字符串
     *
     * @param date 需要转换格式的日期
     * @return 返回短时间字符串格式 yyyy-MM-dd HH:mm:ss
     */
    public static String getFullDateString(Date date) {
        if (date == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * 获取下月月初时间
     */
    public static Date getNextMonthStartTime() {
        return DateUtil.localDate2Date(LocalDateTime.now()
                .with(TemporalAdjusters.lastDayOfMonth()).plusDays(1L).toLocalDate());
    }

    /**
     * @param offsetYear
     * @return 当前时间 + offsetYear
     */
    public static Timestamp getNowExpiredYear(int offsetYear) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.YEAR, offsetYear);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offset
     * @return 当前时间 + offsetMonth
     */
    public static Timestamp getNowExpiredMonth(int offset) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MONTH, offset);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offset
     * @return 当前时间 + offsetDay
     */
    public static Timestamp getNowExpiredDay(int offset) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.DATE, offset);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offset
     * @return 当前时间 + offsetDay
     */
    public static Timestamp getNowExpiredHour(int offset) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.HOUR, offset);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offsetSecond
     * @return 当前时间 + offsetSecond
     */
    public static Timestamp getNowExpiredSecond(int offsetSecond) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.SECOND, offsetSecond);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offset
     * @return 当前时间 + offset
     */
    public static Timestamp getNowExpiredMinute(int offset) {
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, offset);
        return new Timestamp(now.getTime().getTime());
    }

    /**
     * @param offset
     * @return 指定时间 + offsetDay
     */
    public static Timestamp getExpiredDay(Date givenDate, int offset) {
        Calendar date = Calendar.getInstance();
        date.setTime(givenDate);
        date.add(Calendar.DATE, offset);
        return new Timestamp(date.getTime().getTime());
    }

    /**
     * 实现ORACLE中ADD_MONTHS函数功能
     *
     * @param offset
     * @return 指定时间 + offsetMonth
     */
    public static Timestamp getExpiredMonth(Date givenDate, int offset) {
        Calendar date = Calendar.getInstance();
        date.setTime(givenDate);
        date.add(Calendar.MONTH, offset);
        return new Timestamp(date.getTime().getTime());
    }

    /**
     * @param
     * @return 指定时间 + offsetSecond
     */
    public static Timestamp getExpiredYear(Date givenDate, int offsetHour) {
        Calendar date = Calendar.getInstance();
        date.setTime(givenDate);
        date.add(Calendar.YEAR, offsetHour);
        return new Timestamp(date.getTime().getTime());
    }

    /**
     * @param second
     * @return 指定时间 + offsetSecond
     */
    public static Timestamp getExpiredSecond(Date givenDate, int second) {
        Calendar date = Calendar.getInstance();
        date.setTime(givenDate);
        date.add(Calendar.SECOND, second);
        return new Timestamp(date.getTime().getTime());
    }

    /**
     * 计算时间差
     *
     * @param givenDate 日期
     * @param offset    2
     * @param type      日期字段类型
     * @return
     */
    public static Timestamp getExpired(Date givenDate, int offset, Integer type) {
        Calendar date = Calendar.getInstance();
        date.setTime(givenDate);
        date.add(type, offset);
        return new Timestamp(date.getTime().getTime());
    }

    /**
     * 计算日期差
     *
     * @param d1   开始日期
     * @param d2   截止日期
     * @param type 类型
     * @return 计算结果
     */
    public static Integer sub(Date d1, Date d2, String type) {
        if (d1 == null || d2 == null) {
            return null;
        }
        long result = 0L;
        long DAY = 24 * 60 * 60 * 1000;
        long sub = d1.getTime() - d2.getTime();
        long daysub = (sub / DAY);
        long y1 = d1.getYear(), y2 = d2.getYear();
        long m1 = d1.getMonth(), m2 = d2.getMonth();
        long monthsub = (y1 - y2) * 12 + (m1 - m2);
        //月
        if ("m".equals(type)) {
            result = monthsub;
            //年
        } else if ("y".equals(type)) {
            result = monthsub / 12;
            //天
        } else if ("d".equals(type)) {
            result = daysub;
        }
        return (int) result;
    }

    /**
     * 判断是否是凌晨
     *
     * @param date
     * @return
     */
    public static boolean isBeforeDawn(Date date) {
        if (Objects.isNull(date)) {
            return false;
        }
        LocalDateTime dateTime = date2LocalDateTime(date);
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(localDateTime2Date(dateTime));
        int a = Integer.parseInt(str);
        return a >= 0 && a <= 6;
    }

    /**
     * 判断是否是上午
     *
     * @param date
     * @return
     */
    public static boolean isMorning(Date date) {
        if (Objects.isNull(date)) {
            return false;
        }
        LocalDateTime dateTime = date2LocalDateTime(date);
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(localDateTime2Date(dateTime));
        int a = Integer.parseInt(str);
        return a > 6 && a <= 12;
    }

    /**
     * 判断是否是下午
     *
     * @param date
     * @return
     */
    public static boolean isAfternoon(Date date) {
        if (Objects.isNull(date)) {
            return false;
        }
        LocalDateTime dateTime = date2LocalDateTime(date);
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(localDateTime2Date(dateTime));
        int a = Integer.parseInt(str);
        return a > 12 && a <= 18;
    }

    /**
     * 判断是否是晚上
     *
     * @param date
     * @return
     */
    public static boolean isEvening(Date date) {
        if (Objects.isNull(date)) {
            return false;
        }
        LocalDateTime dateTime = date2LocalDateTime(date);
        SimpleDateFormat df = new SimpleDateFormat("HH");
        String str = df.format(localDateTime2Date(dateTime));
        int a = Integer.parseInt(str);
        return a > 18 && a <= 23;
    }

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = format.parse("2020-09-19 09:45:30");
        System.out.println(startDate(getNowExpiredDay(-1)));

        System.out.println(sub(date, new Date(), "d"));
    }
}