DateUtils.java 19.4 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 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
package com.irrigation.icl.utils;

import java.text.ParseException;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * 日期工具类
 *
 * @version 1.0.1
 */
public class DateUtils {


    /**
     * 当前时间,转换为{@link Date}对象
     *
     * @return 当前时间
     */
    public static Date date() {
        return date(currentTimeMillis());
    }


    /**
     * 获取时间
     *
     * @param date 时间戳
     * @return
     */
    public static Date date(Long date) {
        return new Date(date);
    }

    /**
     * 获取指定某一天的开始时间戳
     *
     * @param date
     * @return
     */
    public static Date getDailyStartTime(Date date) {
        Calendar calendar = calendar(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }

    /**
     * 获取指定某一天的结束时间戳
     *
     * @param date
     * @return
     */
    public static Date getDailyEndTime(Date date) {
        Calendar calendar = calendar(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }

    /**
     * 日期加减
     *
     * @param date
     * @param field  对应 Calendar 常量
     * @param amount
     * @return
     */
    public static Date dateFieldAdd(Date date, int field, int amount) {
        Calendar calendar = calendar(date);
        calendar.add(field, amount);
        return calendar.getTime();
    }


    /**
     * 创建Calendar对象,时间为默认时区的当前时间
     *
     * @return Calendar对象
     * @since 4.6.6
     */
    public static Calendar calendar() {
        return Calendar.getInstance();
    }

    /**
     * 转换为Calendar对象
     *
     * @param date 日期对象
     * @return Calendar对象
     */
    public static Calendar calendar(Date date) {
        return calendar(date.getTime());
    }

    /**
     * 转换为Calendar对象
     *
     * @param millis 时间戳
     * @return Calendar对象
     */
    public static Calendar calendar(long millis) {
        final Calendar cal = calendar();
        cal.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        cal.setTimeInMillis(millis);
        return cal;
    }

    private static Calendar toCalendar(Date date) {
        return toCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT), date);
    }


    private static Calendar toCalendar(TimeZone zone, Locale locale, Date date) {
        if (null == locale) {
            locale = Locale.getDefault(Locale.Category.FORMAT);
        }
        final Calendar cal = (null != zone) ? Calendar.getInstance(zone, locale) : Calendar.getInstance(locale);
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        cal.setTime(date);
        return cal;
    }

    /**
     * 当前时间的时间戳
     *
     * @return 时间
     */
    public static long currentTimeMillis() {
        return System.currentTimeMillis();
    }


    /**
     * 当前时间的时间戳(秒)
     *
     * @return 当前时间秒数
     */
    public static long currentSeconds() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 获得年的部分
     *
     * @param date 日期
     * @return 年的部分
     */
    public static int year(Date date) {
        return toCalendar(date).get(Calendar.YEAR);
    }


    /**
     * 获得指定日期所属季度,从1开始计数
     *
     * @param date 日期
     * @return 第几个季度
     * @since 4.1.0
     */
    public static int quarter(Date date) {
        return month(date) / 3 + 1;
    }


    /**
     * 获得月份,从0开始计数
     *
     * @param date 日期
     * @return 月份,从0开始计数
     */
    public static int month(Date date) {
        return toCalendar(date).get(Calendar.MONTH);
    }


    /**
     * 获得指定日期是所在年份的第几周<br>
     *
     * @param date 日期
     * @return 周
     */
    public static int weekOfYear(Date date) {
        return toCalendar(date).get(Calendar.WEEK_OF_YEAR);
    }

    /**
     * 获得指定日期是所在月份的第几周<br>
     *
     * @param date 日期
     * @return 周
     */
    public static int weekOfMonth(Date date) {
        return toCalendar(date).get(Calendar.WEEK_OF_MONTH);
    }

    /**
     * 获得指定日期是这个日期所在月份的第几天<br>
     *
     * @param date 日期
     * @return 天
     */
    public static int dayOfMonth(Date date) {
        return toCalendar(date).get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获得指定日期是星期几,1表示周日,2表示周一
     *
     * @param date 日期
     * @return 天
     */
    public static int dayOfWeek(Date date) {
        return toCalendar(date).get(Calendar.DAY_OF_WEEK);

    }

    /**
     * 获得指定日期的小时数部分<br>
     *
     * @param date 日期
     * @return 小时数
     */
    public static int hour(Date date) {
        return toCalendar(date).get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获得指定日期的分钟数部分<br>
     * 例如:10:04:15.250 =》 4
     *
     * @param date 日期
     * @return 分钟数
     */
    public static int minute(Date date) {
        return toCalendar(date).get(Calendar.MINUTE);

    }

    /**
     * 获得指定日期的秒数部分<br>
     *
     * @param date 日期
     * @return 秒数
     */
    public static int second(Date date) {
        return toCalendar(date).get(Calendar.SECOND);
    }

    /**
     * 获得指定日期的毫秒数部分<br>
     *
     * @param date 日期
     * @return 毫秒数
     */
    public static int millisecond(Date date) {
        return toCalendar(date).get(Calendar.MILLISECOND);

    }

    /**
     * 当前时间,格式 yyyy-MM-dd HH:mm:ss
     *
     * @return 当前时间的标准形式字符串
     */
    public static String now() {
        return formatDateTime(new Date());
    }

    /**
     * 当前日期,格式 yyyy-MM-dd
     *
     * @return 当前日期的标准形式字符串
     */
    public static String today() {
        return formatDate(new Date());
    }

    // ------------------------------------ Format start ----------------------------------------------


    /**
     * 根据特定格式格式化日期
     *
     * @param date    被格式化的日期
     * @param pattern 日期格式,常用格式见:
     * @return 格式化后的字符串
     * @see DatePatternUtils
     */
    public static String format(Date date, String pattern) {
        if (null == date || ObjectUtils.stringIsEmpty(pattern)) {
            return null;
        }
        return DateFormatUtils.getInstance(pattern).format(date);
    }

    /**
     * 格式化日期时间<br>
     * 格式 yyyy-MM-dd HH:mm:ss
     *
     * @param date 被格式化的日期
     * @return 格式化后的日期
     */
    public static String formatDateTime(Date date) {
        if (null == date) {
            return null;
        }
        return DateFormatUtils.NORM_DATETIME_FORMAT.format(date);
    }

    /**
     * 格式化日期部分(不包括时间)<br>
     * 格式 yyyy-MM-dd
     *
     * @param date 被格式化的日期
     * @return 格式化后的字符串
     */
    public static String formatDate(Date date) {
        if (null == date) {
            return null;
        }
        return DateFormatUtils.NORM_DATE_FORMAT.format(date);
    }

    /**
     * 格式化时间<br>
     * 格式 HH:mm:ss
     *
     * @param date 被格式化的日期
     * @return 格式化后的字符串
     * @since 3.0.1
     */
    public static String formatTime(Date date) {
        if (null == date) {
            return null;
        }
        return DateFormatUtils.NORM_TIME_FORMAT.format(date);
    }

    /**
     * 格式化给定样式
     *
     * @param timestamp
     * @param pattern
     * @return
     * @see DatePatternUtils
     */
    public static String format(Long timestamp, String pattern) {
        if (ObjectUtils.isNull(timestamp) || ObjectUtils.isNull(pattern)) {
            return null;
        }
        return DateFormatUtils.getInstance(pattern).format(date(timestamp));
    }

    // ------------------------------------ Format end ----------------------------------------------

    // ------------------------------------ Parse start ----------------------------------------------


    /**
     * 构建DateTime对象
     *
     * @param dateStr Date字符串
     * @param pattern 格式
     * @return DateTime对象
     * @see DatePatternUtils
     */
    public static Date parse(String dateStr, String pattern) {
        try {
            return DateFormatUtils.getInstance(pattern).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将特定格式的日期转换为Date对象
     *
     * @param dateStr 特定格式的日期
     * @param pattern 格式,例如yyyy-MM-dd
     * @param locale  区域信息
     * @return 日期对象
     * @see DatePatternUtils
     * @since 4.5.18
     */
    public static Date parse(String dateStr, String pattern, Locale locale) {
        try {
            return DateFormatUtils.getInstance(pattern, locale).parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 格式yyyy-MM-dd HH:mm:ss
     *
     * @param dateString 标准形式的时间字符串
     * @return 日期对象
     */
    public static Date parseDateTime(String dateString) {
        return parse(dateString, DatePatternUtils.NORM_DATETIME_PATTERN);
    }

    /**
     * 解析格式为yyyy-MM-dd的日期,忽略时分秒
     *
     * @param dateString 标准形式的日期字符串
     * @return 日期对象
     */
    public static Date parseDate(String dateString) {
        return parse(dateString, DatePatternUtils.NORM_DATE_PATTERN);
    }

    /**
     * 解析时间,格式HH:mm:ss,日期部分默认为1970-01-01
     *
     * @param timeString 标准形式的日期字符串
     * @return 日期对象
     */
    public static Date parseTime(String timeString) {
        return parse(timeString, DatePatternUtils.NORM_TIME_PATTERN);
    }

    // ------------------------------------ Parse end ----------------------------------------------

    /**
     * date 转换为 long
     *
     * @param date
     * @return
     */
    public static long dateToLong(Date date) {
        return ObjectUtils.isNull(date) ? 0L : date.getTime();
    }


    /**
     * 时间字符串转换long
     *
     * @param dateStr
     * @param pattern
     * @return
     * @see DatePatternUtils
     */
    public static long dateToLong(String dateStr, String pattern) {
        if (ObjectUtils.isNull(dateStr) || ObjectUtils.isNull(pattern)) {
            return 0L;
        }
        return parse(dateStr, pattern).getTime();
    }

//---------------------new api


    /**
     * 获取指定天的北京时间戳为00:00:00的日期
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static Date getStartTimeOfDay(int year, int month, int day) {
        LocalDate localDate = LocalDate.of(year, month, day);
        Instant instant = localDate.atStartOfDay(ZoneId.of("Asia/Shanghai")).toInstant();
        return Date.from(instant);
    }

    /**
     * 获取某月中第一天北京时间戳为00:00:00的日期
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getStartDateOfMonth(int year, int month) {
        return getStartTimeOfDay(year, month, 1);
    }

    /**
     * 获取某月中最后一天北京时间为23:59:59.999的日期
     *
     * @param year
     * @param month
     * @return
     */
    public static Date getEndDateOfMonth(int year, int month) {
        YearMonth yearMonth = YearMonth.of(year, month);
        LocalDate endOfMonth = yearMonth.atEndOfMonth();
        LocalDateTime localDateTime = endOfMonth.atTime(23, 59, 59, 999);
        ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.of("Asia/Shanghai"));
        return Date.from(zonedDateTime.toInstant());
    }

    /**
     * 获得指定年北京时间0点的开始时间戳
     *
     * @param year
     * @return
     */
    public static long getYearStartMilliseconds(Integer year) {
        return LocalDateTime.of(year, 1, 1, 0, 0, 0, 0).toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 获得指定年北京时间最后一毫秒的时间戳
     *
     * @param year
     * @return
     */
    public static long getYearEndMilliseconds(Integer year) {
        return getYearStartMilliseconds(year + 1) - 1;
    }

    /**
     * 获得指定日期北京时间0点的时间戳
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static long getDayStartMilliseconds(Integer year, Integer month, Integer day) {
        return LocalDateTime.of(year, month, day, 0, 0, 0, 0).toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 获取指定日期北京时间23:59:59.999的时间戳
     *
     * @param year
     * @param month
     * @param day
     * @return
     */
    public static long getDayEndMilliseconds(Integer year, Integer month, Integer day) {
        return LocalDateTime.of(year, month, day, 23, 59, 59, 999).toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 获取传入时间戳所指向日期北京时间0点的时间戳
     *
     * @param timestamp
     * @return
     */
    public static long getDayStartTimeStamp(Long timestamp) {
        LocalDateTime time2 = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8));
        LocalDate localDate = time2.toLocalDate();
        return localDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli();
    }

    /**
     * 获取传入时间戳所指向日期北京时间23:59:59.999的时间戳
     *
     * @param timestamp
     * @return
     */
    public static long getDayEndTimeStamp(Long timestamp) {
        LocalDateTime time2 = LocalDateTime.ofEpochSecond(timestamp / 1000, 0, ZoneOffset.ofHours(8)).plusDays(1L);
        LocalDate localDate = time2.toLocalDate();
        return localDate.atStartOfDay().toInstant(ZoneOffset.of("+8")).toEpochMilli() - 1L;
    }


    /**
     * 获取指定月北京时间1月1日0点的时间戳
     *
     * @param month
     * @return
     */
    public static long getStartTimestampOfMonth(int month) {
        YearMonth yearMonth = YearMonth.now(ZoneId.of("Asia/Shanghai"));
        return getDayStartMilliseconds(yearMonth.getYear(), month, 1);
    }

    /**
     * 获取当年一月的格式化字符串 yyyy-MM
     *
     * @return
     */
    public static String getJanuary() {
        YearMonth yearMonth = YearMonth.now().withMonth(1);
        return yearMonth.format(DateTimeFormatter.ofPattern(DatePatternUtils.NORM_YM_PATTERN));
    }

    /**
     * 获取当月格式化字符串 yyyy-MM
     *
     * @return
     */
    public static String getCurrentMonth() {
        LocalDate now = LocalDate.now(ZoneId.of("Asia/Shanghai"));
        return now.format(DateTimeFormatter.ofPattern(DatePatternUtils.NORM_YM_PATTERN));
    }

    /**
     * 通过时间戳获取前一日北京日期
     *
     * @param timestamp
     * @return
     */
    public static Date yesterday(Long timestamp) {
        LocalDateTime time2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.of("Asia/Shanghai")).minusDays(1L);
        return Date.from(time2.toInstant(ZoneOffset.ofHours(8)));
    }

    /**
     * 将时间戳转换为北京日期
     *
     * @param timestamp
     * @return
     */
    public static Date convertTimestampToDate(Long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.ofHours(8)).toInstant();
        return Date.from(instant);

    }

    /**
     * 获取timestamp+8小时的日期,专用于MongoDB查询
     *
     * @param timestamp
     * @return
     */
    public static Date getYesterdayUtcDate(Long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp).plus(8L, ChronoUnit.HOURS).minus(1L, ChronoUnit.DAYS);
        return Date.from(instant);
    }


    /**
     * 获取+8小时时间戳的日期,专用于MongoDB查询
     *
     * @param timestamp
     * @return
     */
    public static Date convertTimestampToUtcDate(Long timestamp) {
        Instant instant = Instant.ofEpochMilli(timestamp).plus(8, ChronoUnit.HOURS);
        return Date.from(instant);
    }

    /**
     * 获取日期
     *
     * @return 如:2014-12-10
     */
    public static LocalDate getLocalDateNow() {
        return LocalDate.now();
    }

    /**
     * 获取日期
     *
     * @param year
     * @param month
     * @param dayOfMont
     * @return 如:2014-12-10
     */
    public static LocalDate getLocalDate(int year, int month, int dayOfMont) {
        return LocalDate.of(year, month, dayOfMont);
    }

    /**
     * 获取时间
     *
     * @return 如:14:29:40.558
     */
    public static LocalTime getLocalTimeNow() {
        return LocalTime.now();
    }

    /**
     * 获取时间
     *
     * @return 14:29:40
     */
    public static LocalTime getLocalTimeNowOfSecond() {
        return getLocalTimeNow().withNano(0);
    }

    /**
     * 获取指定时间
     *
     * @param hour
     * @param minute
     * @param second
     * @param nanoOfSecond
     * @return
     */
    public static LocalTime getLocalTime(int hour, int minute, int second, int nanoOfSecond) {
        return LocalTime.of(hour, minute, second, nanoOfSecond);
    }

    /**
     * 获取时间和日期
     *
     * @return 如:2016-11-06T15:20:27.996
     */
    public static LocalDateTime getLocalDateTimeNow() {
        return LocalDateTime.now();
    }

    /**
     * 获取时间和日期
     *
     * @param year
     * @param month
     * @param dayOfMonth
     * @param hour
     * @param minute
     * @param second
     * @param nanoOfSecond
     * @return
     */
    public static LocalDateTime getLocalDateTime(int year, int month, int dayOfMonth, int hour, int minute, int second, int nanoOfSecond) {
        return LocalDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoOfSecond);


    }

    /**
     * LocalDateTime 格式化
     *
     * @param localDateTime
     * @param pattern
     * @return
     * @see DatePatternUtils
     */
    public static String format(LocalDateTime localDateTime, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(localDateTime);
    }

    /**
     * LocalDate 格式化
     *
     * @param localDate
     * @param pattern
     * @return
     */
    public static String format(LocalDate localDate, String pattern) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern);
        return dateTimeFormatter.format(localDate);
    }

    /**
     * 获取当前时间字符串 :2019-09-01
     * @return
     */
    public static String formatDateNow() {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(DatePatternUtils.NORM_DATE_PATTERN);
        return dateTimeFormatter.format(getLocalDateNow());
    }


}