DateUtil

Origin

Considering the limited support for dates and times in Java itself, and the coexistence of Date and Calendar objects leading to confusion and complexity in the use of various methods, this utility class was used for encapsulation. The encapsulation here is mainly about the conversion between dates and strings, as well as providing ways to locate dates (one month ago, etc.).

For Date objects, for convenience, a DateTime class was used instead, inheriting from the Date object. The main convenience lies in overriding the toString() method to return a string in the form of yyyy-MM-dd HH:mm:ss, which is convenient for output such as log recording. It provides many convenient methods for operating on date objects. More information about DateTime will be introduced in relevant chapters.

Methods

Conversions

Mutual conversions between Date, long, and Calendar

// Current time
Date date = DateUtil.date();
// Current time
Date date2 = DateUtil.date(Calendar.getInstance());
// Current time
Date date3 = DateUtil.date(System.currentTimeMillis());
// Current time string, format: yyyy-MM-dd HH:mm:ss
String now = DateUtil.now();
// Current date string, format: yyyy-MM-dd
String today= DateUtil.today();

String to date conversion

The DateUtil.parse method can automatically recognize some common formats, including:

yyyy-MM-dd HH:mm:ss

  • yyyy/MM/dd HH:mm:ss
  • yyyy.MM.dd HH:mm:ss
  • yyyy年MM月dd日 HH时mm分ss秒
  • yyyy-MM-dd
  • yyyy/MM/dd
  • yyyy.MM.dd
  • HH:mm:ss
  • HH时mm分ss秒
  • yyyy-MM-dd HH:mm
  • yyyy-MM-dd HH:mm:ss.SSS
  • yyyyMMddHHmmss
  • yyyyMMddHHmmssSSS
  • yyyyMMdd
  • EEE, dd MMM yyyy HH:mm:ss z
  • EEE MMM dd HH:mm:ss zzz yyyy
  • yyyy-MM-dd’T’HH:mm:ss’Z'
  • yyyy-MM-dd’T’HH:mm:ss.SSS’Z'
  • yyyy-MM-dd’T’HH:mm:ssZ
  • yyyy-MM-dd’T’HH:mm:ss.SSSZ
String dateStr = "2017-03-01";
Date date = DateUtil.parse(dateStr);

We can also use custom date formats for conversion:

String dateStr = "2017-03-01";
Date date = DateUtil.parse(dateStr, "yyyy-MM-dd");

Formatting Dates for Output

String dateStr = "2017-03-01";
Date date = DateUtil.parse(dateStr);

// Result: 2017/03/01
String format = DateUtil.format(date, "yyyy/MM/dd");

// Common format formatting, result: 2017-03-01
String formatDate = DateUtil.formatDate(date);

// Result: 2017-03-01 00:00:00
String formatDateTime = DateUtil.formatDateTime(date);

// Result: 00:00:00
String formatTime = DateUtil.formatTime(date);

Obtaining a specific part of a Date object

Date date = DateUtil.date();
// Obtain the year part
DateUtil.year(date);
// Obtain the month part, counting from 0
DateUtil.month(date);
// Obtain the month enum
DateUtil.monthEnum(date);
// ...

Starting and ending time

Sometimes we need to get the starting and ending time of each day, month, etc. DateUtil provides related methods:

String dateStr = "2017-03-01 22:33:23";
Date date = DateUtil.parse(dateStr);

// The starting time of the day, result: 2017-03-01 00:00:00
Date beginOfDay = DateUtil.beginOfDay(date);

// The ending time of the day, result: 2017-03-01 23:59:59
Date endOfDay = DateUtil.endOfDay(date);

Date and time offset

Date or time offset refers to adding or subtracting minutes, hours, days, etc., from a specific date to achieve date changes. Hutool has done a lot of encapsulation for this purpose

String dateStr = "2017-03-01 22:33:23";
Date date = DateUtil.parse(dateStr);

// Result: 2017-03-03 22:33:23
Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 2);

// Common offset, result: 2017-03-04 22:33:23
DateTime newDate2 = DateUtil.offsetDay(date, 3);

// Common offset, result: 2017-03-01 19:33:23
DateTime newDate3 = DateUtil.offsetHour(date, -3);

For the current time, simplified offset methods are provided (e.g., yesterday, last week, last month, next month):

// Yesterday's date
DateUtil.yesterday()
// Tomorrow's date
DateUtil.tomorrow()
// Last week's date
DateUtil.lastWeek()
// Next week's date
DateUtil.nextWeek()
// Last month's date
DateUtil.lastMonth()
// Next month's date
DateUtil.nextMonth()

Calculating the difference between two dates

Sometimes we need to calculate the time difference between two dates (in days, hours, etc.), which is encapsulated by Hutool as the between method:

String dateStr1 = "2017-03-01 22:33:23";
Date date1 = DateUtil.parse(dateStr1);

String dateStr2 = "2017-04-01 23:33:23";
Date date2 = DateUtil.parse(dateStr2);

// Difference of one month, 31 days
long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY);

Formatting time difference for easy reading Sometimes we want to see an easy-to-read time difference, such as XX days XX hours XX minutes XX seconds, which can be achieved using the DateUtil.formatBetween method:

String level = "MINUTE"; 
// Specify the level to be minute accuracy 
String formatBetween = DateUtil.formatBetween(between, Level.MINUTE); 
// Output: 31 days 1 hour
Console.log(formatBetween);

Zodiac and Chinese Zodiac

// "Capricorn"
String zodiac = DateUtil.getZodiac(Month.JANUARY.getValue(), 19);

// "Dog"
String chineseZodiac = DateUtil.getChineseZodiac(1994);

Date Ranges

// Creating a date range generator
DateTime start = DateUtil.parse("2021-01-31");
DateTime end = DateUtil.parse("2021-03-31");
DateRange range = DateUtil.range(start, end, DateField.MONTH);

// Easy usage
// Start range
DateRange startRange = DateUtil.range(DateUtil.parse("2017-01-01"), DateUtil.parse("2017-01-31"), DateField.DAY_OF_YEAR);
// End range
DateRange endRange = DateUtil.range(DateUtil.parse("2017-01-31"), DateUtil.parse("2017-02-02"), DateField.DAY_OF_YEAR);
// Intersection returns [2017-01-31 00:00:00]
List<DateTime> dateTimes = DateUtil.rangeContains(startRange, endRange);
// Difference returns [2017-02-01 00:00:00, 2017-02-02 00:00:00]
List<DateTime> dateNotTimes = DateUtil.rangeNotContains(startRange, endRange);
// Range to list returns [2017-01-01 00:00:00, 2017-01-02 00:00:00, 2017-01-03 00:00:00]
List<DateTime> rangeToList = DateUtil.rangeToList(DateUtil.parse("2017-01-01"), DateUtil.parse("2017-01-03"), DateField.DAY_OF_YEAR);

Other Functions

// Calculate age based on current date and birthdate "1990-01-30"
DateUtil.ageOfNow("1990-01-30");

// Check if a year is a leap year
DateUtil.isLeapYear(2017);