SoFunction
Updated on 2025-05-11

Detailed explanation of the use of a replacement for DateUtils native Java date

Preface

Hello time travelers! What I want to introduce today is the DateUtils tool class in Apache Commons Lang3. This tool is like the "time machine" in the programming world, allowing you to turn around gracefully in the quagmire of date processing and say goodbye from now onCalendarThose APIs!

1. Why DateUtils are needed

Native Java date operations are like:

  • (): The parameters are as mysterious as horoscopes (FIELD parameters are all int magic numbers)
  • How many days does it take to calculate the difference between the two dates? Write your own loop!
  • Want to ignore time comparison dates? Let's set it to midnight first...

And DateUtils is your "Time Swiss Army Knife":

// Stone Age writingCalendar cal = ();
(Calendar.DAY_OF_MONTH, 1); // Add 1 dayDate tomorrow = ();
// How to write in the civilized eraDate tomorrow = (new Date(), 1);

2. DateUtils' time manipulation technique

1. Date addition and subtraction

// Basic addition and subtractionDate now = new Date();
Date yesterday = (now, -1); // yesterdayDate nextHour = (now, 1);  // In one hour// Supported time units:// MILLISECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, YEAR

2. Date Comparator

// Determine whether it is the same dayboolean sameDay = (date1, date2);
// Ignore time comparisonint compare = (date1, date2, );

3. Date truncation technique

// Get 0:00 on the dayDate midnight = (now, );
// Get the first day of the monthDate firstDayOfMonth = (now, );

4. Date rounding method

// Round to the nearest hourDate nearestHour = (now, );
// Round up until tomorrowDate ceilingDay = (now, );

3. Actual time magic

1. Calculate how many days will you have to have a birthday

Date birthday = new GregorianCalendar(1990, , 15).getTime();
Date nextBirthday = (birthday, ().getValue());
if((new Date())) {
    nextBirthday = (nextBirthday, 1);
}
long daysUntilBirthday = (() - new Date().getTime()) / (1000 * 60 * 60 * 24);

2. Generate date range

// Get all dates of the weekList<Date> weekDates = new ArrayList<>();
Date monday = ((new Date(), -Calendar.DAY_OF_WEEK + 2), );
for(int i=0; i<7; i++) {
    ((monday, i));
}

3. Time zone conversion assistance

// Use with TimeZoneTimeZone laTime = ("America/Los_Angeles");
Date laDate = (new Date(), 
    (new Date().getTime()) / (1000 * 60 * 60));

4. DateUtils' time and space code

  • Immutability: All methods return the new Date object, the original object remains unchanged
  • Thread safety: No shared state, use it with confidence
  • Performance tips: It is recommended to use frequentlyCalendarExample reuse
  • Time zone warning: The system time zone is used by default, and additional processing is required across time zones.

5. Space-time dialogue with modern APIs

// Java 8+ alternative (recommended)LocalDate tomorrow = ().plusDays(1);
Instant truncated = ().truncatedTo();
// Compare with Joda-Time (transition plan)DateTime jodaTime = new DateTime().plusDays(1);

6. Version change memorandum

  • Java 7 and before: DateUtils is the savior of date processing
  • Java 8+: It is recommended to gradually migrate toBag
  • Future trend: Recommended use of new projects+DateTimeUtils

7. Summary

DateUtils is like:

  • "Abacus Master" of Date Calculation
  • The "referee" of time comparison
  • "Translation Officer" for date formatting
  • "Anti-dead design" for time operation

Attached is a quick checklist for date operation:

need DateUtils solution Java 8+ alternatives
Add N days addDays(date, N) (N)
Judgment on the same day isSameDay(date1,2) ()
Get the first day of the month truncate(date, MONTH) (1)
Ignore time comparison truncatedCompareTo() ()

The above is the detailed explanation of the use of the replacement of DateUtils native Java dates. For more information about Java DateUtils, please pay attention to my other related articles!