Very powerful java time processing tool class!

xk-time is a tool for time conversion, time calculation, time formatting, time parsing, calendar, time cron expression and time NLP, etc. It uses Java8, thread-safe, simple and easy to use, as many as 70 commonly used date formatting templates , Support Java8 time class and Date, lightweight, no third-party dependencies.

 

Why develop this tool?

(1) The Date API before Java 8 is not well designed, it is inconvenient to use, and thread safety problems often occur.

The xk-time toolkit uses java8 api. Among them, Instant, LocalDate, LocalDateTime, LocalTime, ZonedDateTime, etc. are all thread-safe classes, and a richer method is added. On this basis, relevant tool classes are developed, thread-safe, and let use more convenient.

(2) Common DateUtil often puts functions such as time conversion, calculation, formatting, and parsing in the same class, resulting in complicated class functions, too many methods, and inconvenient search.

The xk-time toolkit divides the above functions into 3 tool classes according to time conversion, time calculation, and time formatting analysis: DateTimeConverterUtil, DateTimeCalculatorUtil, DateTimeFormatterUtil, each class only has one function, which is convenient to use.

(3) In order to integrate the functions of holidays, lunar calendar, twenty-four solar terms, twelve constellations, twelve zodiac signs, twelve hours, and calendars that are closely related to time into tools for easy use.

Main function description

1. Date conversion tool class DateTimeConverterUtil

Including Date, LocalDate, LocalDateTime, LocalTime, Instant, ZonedDateTime, YearMonth, Timestamp, and long.    
Note that the conversion of ZonedDateTime, especially the conversion of other times to ZonedDateTime, should be consistent with the corresponding time zone.

For detailed use, you can view the relevant test code.

2. Date calculation tool class DateTimeCalculatorUtil

Including: 
(1) Get time attribute method (support year, month, day, hour, minute, second, millisecond, week, timestamp, etc.), get* such as getYear(Date date) to get year part, getMonthCnLong(Date date) to get month Chinese, getDayOfWeekCn(Date date) ), get the Chinese of the week.

(2) Get the time plus operation method, plus* such as plusYears(Date date, long amountToAdd) The current time year increases the value of amountToAdd.

(3) Get the time subtraction operation method, minus* such as minusYears(Date date, long amountToSubtract) The current time year reduces the amountToSubtract value.

(4) Get the time to modify the attribute method, with* such as withYear(Date date, long newValue) to modify the current time year value to newValue.

(5) Get and compare two time methods, such as betweenYears(Date startInclusive, Date endExclusive) Compare two times and get the year part.

(6) Other commonly used methods, such as isLeapYear(Date date) to determine whether a leap year, isWeekend(Date date) to determine whether it is a weekend, isExpiry(String yearMonthStr) whether to expire, etc.

(7) Time zone conversion calculation method, transform*, such as transform(ZonedDateTime zonedDateTime, String zoneId)

(8) Compare two time size and equality methods, compare*, such as compare(Date date1, Date date2)

(9) Get the accurate start time method, start , end , such as startTimeOfMonth() the start time of the current month, the first day of the month + 00:00:00, endTimeOfMonth() the last day of the month + 23:59:59 accurate to Seconds; endAccuracyTimeOf*, accurate to milliseconds (Date), accurate to nanoseconds (LocalDateTime).

(10) The same month and day comparison judgment method, isSameMonthDay , betweenNextSameMonthDay , nextSameMonthDay*, for example, for birthdays, holidays and other periodic date comparison judgments.

(11) Constellation calculation method, getConstellation*, such as getConstellationNameCn(String monthDayStr), calculate the constellation based on the date.

(12) Calculate the time list of the specified year and month or the starting time interval, get*List, such as getDateList(int year, int month), calculate the time list of the specified year and month.

(13) Reduce the time accuracy method, reduceAccuracyTo*, such as reduceAccuracyToDay(Date date), reduce the time accuracy to days, and add 0 to others, and return such as 2020-04-23 00:00:00.

(14) Get the timestamp method, getEpoch*, such as getEpochMilli() to get the timestamp, getEpochMilliFormat() to get the timestamp format string (yyyy-MM-dd HH:mm:ss)

(15) Age calculation method, getAge*, such as getAge(Date birthDay), calculate age by birthday.

(16) The method of judging whether it is birthday, isBirthDay*, such as isBirthDay(Date birthDay), to judge whether the current date is birthday according to the birthday.

(17) The calculation method of week number, weekof*, such as weekOfMonth(Date date), the week of the month where the date is located.

(18) Determine whether Monday, Friday, isMonday , isZhouYi , such as isZhouYi(Date date), whether it is Monday.

(19) The twelve hour calculation method, getTwelveTwo*, such as getTwelveTwo(Date date), obtains the twelve hour corresponding to the specified time.

(20) Quarter calculation method, getQuarter*, such as getQuarter(Date date), to obtain the quarter corresponding to the specified time.

(21) Get the accurate start time method of the quarter (four quarters), startTimeOf*Quarter, such as startTimeOfFirstQuarter(int year), get the first quarter of the specified year.

(22) Get the accurate start time method of the year, startTimeOfYear, such as startTimeOfYear(int year), get the start time of the specified year.

(23) Common time calculation methods (tomorrow, next week, next month, next year, etc.), such as tomorrow(), calculate tomorrow and return Date.

(24) Modify the week value method withDayOfWeek*, such as withDayOfWeek(Date date, long newValue), modify the day of the week to the specified value newValue, and return Date.

(25) Chinese working day calculation (including holiday information), including methods to determine whether the current date is a working day and the next working day, isChineseWorkDay , nextChineseWorkDay ,  
such as isChineseWorkDay(Date, String holidayData), nextChineseWorkDay(Date date, String holidayData),  
holidayData. If the holiday data does not support the year, it will use Monday to Friday as working days to judge.

For detailed use, you can view the relevant test code.

3. Date formatting and parsing tool class DateTimeFormatterUtil

Include common date formats such as: 
yyyy-MM-dd  
HH:mm:ss  
yyyy-MM-dd HH:mm:ss  
yyyy-MM-dd HH:mm:ss.SSS  
yyyy-MM-dd HH:mm:ss.SSSSSS  
yyyy-MM-dd HH:mm:ss.SSSSSSSSS  
yyyy-MM-dd'T'HH:mm:ssZ, etc., supports precise time such as milliseconds, microseconds and nanoseconds.

(1) Formatting method, format*, such as formatToDateStr(Date date), returns the date part, such as: yyyy-MM-dd;  
format(Date date, DateTimeFormatter formatter) formatter can choose a defined formatter such as YYYY_MM_DD_HH_MM_SS_FMT( yyyy-MM-dd HH:mm:ss) format the date.

(2) Parsing method, parse*, for example, parseDateStrToDate(String text) parses the date yyyy-MM-dd, and returns Date; 
parseToDate(String text, DateTimeFormatter formatter) parses into Date according to formatter.

(3) Automatic parsing method, automatic identification and parsing according to the characteristics of the string, smartParse*, such as smartParseToDate(String text), automatically parsing Date.

(4) ISO format (including T) automatic parsing method, automatic identification and parsing according to the characteristics of the string, parseIso*, such as parseIsoToDate(String text), automatically parsing Date.

(5) Parse the timestamp method, parseEpochMilli*, such as parseEpochMilliToDate(String text), and parse the time stamp as Date, such as 1590224790000.

(6) Parse the default format of Date, parseDateDefaultStr*, such as parseDateDefaultStrToDate(String text)  
Parse EEE MMM dd HH:mm:ss zzz yyyy For example: Sat May 23 17:06:30 CST 2020 is Date.

(7) Custom time zone formatting methods, such as format(Date date, DateTimeFormatter formatter, String zoneId), format Date according to zoneId.

(8) Custom template formatting methods, such as format(Date date, String dateFormatPattern), format Date according to dateFormatPattern.

(9) Custom template parsing methods, such as parseToDate(String text, String dateFormatPattern), format Date according to dateFormatPattern.

(10) Timestamp default format (yyyy-mm-dd hh:mm:ss.fffffffff where fffffffff is nanoseconds, omit the following 0) formatting method.   
For example, formatTimestampStyle(Date date).

(11) Timestamp default format (yyyy-mm-dd hh:mm:ss.fffffffff where fffffffff is nanoseconds, omit the following 0) parsing method.   
For example, parseTimestampStyleToDate(String text).

(12) The method to verify whether the date format is correct, isValidDate*, such as isValidDate(String text), to verify whether the yyyy-MM-dd format string is correct.

(13) According to the custom template array parsing method, such as parseToDate(String text, String[] dateFormatPatterns), dateFormatPatterns supports multiple templates, as long as one of them is successfully parsed, the corresponding Date will be returned.

(14) Parsing natural language time, today, tomorrow, next week, next month, next year, yesterday, last week, last month, last year, etc., such as parseNaturalLanguageToDate(String text),  
parseNaturalLanguageToDate(String text, MapnaturalLanguageMap) Support custom parsing natural Language time map

Note: When formatting and parsing a time that is different from the system time zone, use the custom time zone formatting method, or use the withZone method to reset the time zone, such as: 
YYYY_MM_DD_HH_MM_SS_SSS_FMT.withZone(ZoneId.of("Europe/Paris")).

For detailed use, you can view the relevant test code.

4. Calendar tool class CalendarUtil

Including: 
(1) The method of generating a calendar at a specified time (calendar containing a hierarchical relationship between year, month and day), generateCalendar* For example, generateCalendar(int year, int month) generates a calendar for a specified year and month.  
(2) Generate a calendar at a specified time (calendar including the hierarchical relationship between year, month and day), including the lunar calendar and all holiday information methods, generateCalendarWithHoliday*, which is better than generateCalendarWithHoliday(int year, int month, MaplocalHolidayMap, MapchineseHolidayMap, MapdateTypeMap) The monthly calendar contains the lunar calendar and all holidays information, and can customize holidays and working days.

For detailed use, you can view the relevant test code.

5. Lunar Date Class LunarDate

Contains: 
(1) Calculation of lunar date, year, month and day. 
(2) The lunar calendar years, the zodiac signs are calculated. 
(3) Twenty-four solar terms calculation, etc.  
Note: Only support the conversion of the Gregorian calendar from 1900 to 2100

For detailed use, you can view the relevant test code.

6. Holiday Util

Include: 
(1) Gregorian calendar holiday calculation, getLocalHoliday* For example, getLocalHoliday(Date date) calculates the Gregorian holiday of date, getLocalHoliday(Date date, MaplocalHolidayMap) can pass in custom Gregorian holiday data.  
(2) Lunar holidays calculation, getChineseHoliday* For example, getChineseHoliday(Date date) calculates the lunar holiday of date, getChineseHoliday(Date date, MapchineseHolidayMap) can pass in custom lunar holiday data. 
(3) Calculation of twenty-four solar terms, getSolarTerm* For example, getSolarTerm(Date date) calculates the twenty-four solar terms of date.

Note: The lunar calendar and the twenty-four solar terms use the lunar date class LunarDate, which only supports the calculation of the Gregorian calendar from 1900 to 2100.

For detailed use, you can view the relevant test code.

7. Cron expression tool class CronExpressionUtil

Cron expressions from left to right (separated by spaces): seconds (0-59) minutes (0-59) hours (0-23) date (1-31) month (integer of 1-12 or JAN-DEC) Week (1-7 integer or SUN-SAT (1=SUN)) Year (optional, 1970-2099)  
Special characters can be used in all fields:,-* / are enumeration, range, arbitrary, interval  
date separately Available:? LW is arbitrary, and finally, the effective working day (Monday to Friday)  
week can also be used:? L # are arbitrary, and finally, the first few weeks of each month  
commonly used cron expressions: 
(1) 0 0 2 1 *? * Means to trigger at 2 am on the 1st of each month  
(2) 0 15 10? * MON-FRI means to execute the job at 10:15 every day from Monday to Friday  
(3) 0 15 10? * 6L 2002-2006 means the execution at 10:15 am on the last Friday of each month from 2002 to 2006  
(4) 0 0/30 9-17 * *? Every half an hour during working hours from 9 to 5  
(5) 0 15 10 L *? Triggered at 10:15 am on the last day of each month  
(6) 0 15 10? * 6#3 Triggered at 10:15 am on the third Friday of each month

Contains  
(1) validation and formatting Cron expression methods, isValidExpression and formatExpression. 
(2) Generate the next one or more execution time methods, getNextTime and getNextTimeList. 
(3) Generate the date formatting (yyyy-MM-dd HH:mm:ss) method of the next one or more execution times, getNextTimeStr and getNextTimeStrList. 
(4) Compare whether the next execution time of the Cron expression is equal to the specified date method, isSatisfiedBy.

Note: The bottom layer is processed by quartz's CronExpression.

For detailed use, you can view the relevant test code.

8. Calculate time-consuming tool CostUtil

Calculation time-consuming tool, support seconds, milliseconds, nanoseconds

Including: 
(1) Calculate time-consuming and return time-consuming results. 
(2) Calculate time-consuming, customize task name, and output time-consuming result. 
(3) The calculation is time-consuming, returns accurate timing, results with 3 decimals, and uses ROUND_DOWN to discard decimals that exceed 3 digits.

For detailed use, you can view the relevant test code.

9. Time Natural Language Analysis Tool (NLP) TimeNLPUtil

Including functions:  
(1) Analyze time natural language based on current time. 
(2) Analyze the natural language of time based on the specified time.

Modified from https://github.com/shinyke/Time-NLP and  
made some modifications as follows: 
(1) Encapsulate attributes and rename them to conform to the camel case naming standard. 
(2) Change the regular resource file loading to singleton loading. 
(3) Re-divide the classes into separate classes according to their functions. 
(4) Rewrite using Java8 date API. 
(5) Add notes and optimize the code.  
(6) Fix the issues in the original project: standard time yyyy-MM-dd, yyyy-MM-dd HH:mm:ss and yyyy-MM-dd HH:mm parsing issues.  
(7) Fix the issues in the original project: after 1 hour, 1 and a half hours, 1 hour and 50 minutes, etc., the resolution problem; and support to seconds, such as 50 seconds, 10 minutes and 30 seconds.    
(8) Repair the issue in the original project: Repair the current time at 10 am, then 3 pm will be recognized as the 3 pm problem tomorrow afternoon.  
(9) Repair the issue in the original project: Repair the decimal parsing abnormal problem.

Note: NLP will have a certain recognition failure rate, and iterative development is constantly improving the success rate.

 

Installation project

(1)Maven

<dependency>  
  <groupId>com.github.xkzhangsan</groupId>    
  <artifactId>xk-time</artifactId>       
  <version>3.0.1</version>    
</dependency> 

(2)Gradle

compile group: 'com.github.xkzhangsan', name: 'xk-time', version: '3.0.1'  

Note: Use Android with caution. The Android side does not support Java 8 because it needs to be compatible with lower versions. It is recommended to continue to use other tools. If you need the functions related to this project, you can refer to the source code for implementation, or leave a message to me. Thanks for the support!

 

Code download    https://download.csdn.net/download/u011694328/14928138

Guess you like

Origin blog.csdn.net/u011694328/article/details/113104145