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, easy to use, and more than 70 common date formatting templates , Support Java8 time class and Date, lightweight, no third-party dependencies.
<dependency>
<groupId>com.github.xkzhangsan</groupId>
<artifactId>xk-time</artifactId>
<version>3.2.4</version>
</dependency>
Mini版本不包含 time nlp 功能,更简洁。
<dependency>
<groupId>com.github.xkzhangsan</groupId>
<artifactId>xk-time</artifactId>
<version>3.2.4.Mini</version>
</dependency>
compile group: 'com.github.xkzhangsan', name: 'xk-time', version: '3.2.4'
xk-time toolkit uses java8 api, among which Instant, LocalDate, LocalDateTime, LocalTime, ZonedDateTime, etc. are all thread-safe classes, and richer methods have been added. On this basis, related tool classes are developed to make them more thread-safe, making them more convenient to use.
xk-time toolkit, the above functions are divided into 3 tool classes according to time conversion, time calculation, and time formatting and analysis: DateTimeConverterUtil, DateTimeCalculatorUtil, and DateTimeFormatterUtil. Each class only has one function for easy use.
2.4.1 The implementation of joda-time and Java8 time packages are basically the same, both dominated by Stephen Colebourne. Starting from Java8, it is recommended to use the java8 time package to replace joda-time.
2.4.2 xk-time is based on the Java 8 date api and is a supplementary tool, similar to the previous dateutil.
(1) The Java8 class library is implemented vertically at a hierarchical level, while xk-time is divided into 3 classes according to general functions, such as conversion, calculation, formatting and analysis.
(2) Java8 Date is converted into a new class, and you need to view the API documentation, and xk-time is converted internally, so that Date can directly use the new features of Java8.
(3) xk-time re-implements the commonly used functions of dateutil according to the Java 8 API, and at the same time, some extensions are made to make use more convenient.
Include:
(1) Date, LocalDate, LocalDateTime, LocalTime, Instant, ZonedDateTime, YearMonth, Timestamp, Timestamp and TemporalAccessor are converted to each other.
(2) Time units such as days, hours, minutes, seconds and milliseconds are converted to each other, supporting the precise conversion of small units to large units. For example, minuteToHourPrecise(long num) 90 minutes to hours, which is 1.5 hours.
(3) Convert ZonedDateTime while supporting conversion to a specified time zone, such as toZonedDateTime(Date date, String zoneId) and toZonedDateTimeAndTransformZone(LocalDateTime localDateTime, String targetZoneId).
Note that for ZonedDateTime related conversions, especially for other time conversions to ZonedDateTime, you should pay attention to the consistency of the time and the corresponding time zone.
For detailed use, you can view the relevant test code: DateTimeConverterUtilTest.
include:
(1) Get the time attribute method (supports year, month, hour, minute, millisecond, week, time stamp, etc.), get* For example, getYear(Date date) gets the year part, getMonthCnLong(Date date) gets the month Chinese, getDayOfWeekCn(Date date), get the week Chinese.
(2) Get the time plus operation method, plus* For example, plusYears(Date date, long amountToAdd) Increase the amountToAdd value in the current time year.
(3) Obtain the time-decrease operation method, minus* For example, minusYears(Date date, long amountToSubtract) The current time-year decreases the amountToSubtract value.
(4) Get the time modification attribute method, with* For example, withYear(Date date, long newValue) to modify the current time and year value to newValue.
(5) Get 2 times to compare, between* For example, betweenTotalDays(Date startInclusive, Date endExclusive) Compare 2 times to return the total number of days.
(6) Other common methods, such as isLeapYear(Date date) to determine whether it is a leap year, isWeekend(Date date) to determine whether it is a weekend, isExpiry(String yearMonthStr) to expire, etc.
(7) Time zone conversion calculation method, transform*, such as transform(ZonedDateTime zonedDateTime, String zoneId)
(8) Compare 2 times and equality methods, compare*, such as compare(Date date1, Date date2)
(9) Obtain the exact start time method, start*, end*, such as startTimeOfMonth() start time of the month first day date +00:00:00, endTimeOfMonth() last day date +23:59:59 accurate to seconds; endAccuracyTimeOf*, accurate to milliseconds (Date), accurate to nanoseconds (LocalDateTime).
(10) Methods for comparing and judging the same month and day, isSameMonthDay*, betweenNextSameMonthDay*, nextSameMonthDay*, for example, for periodic date comparison judgments such as birthdays, festivals, etc.
(11) Constellation calculation method, getConstellation*, such as getConstellationNameCn(String monthDayStr), calculates constellations based on date.
(12) Calculate the time list of the specified year and month or starting time interval, get*List, such as getDateList(int year, int month), calculates the time list of the specified year and month.
(13) Method for reducing time accuracy, reduceAccuracyTo*, such as reduceAccuracyToDay(Date date), reduce time accuracy to days, and add 0 to other methods, return, for example, 2020-04-23 00:00:00.
(14) Get the timestamp method, getEpoch*, for example getEpochMilli() gets the timestamp, getEpochMilliFormat() gets the timestamp format string (yyyy-MM-dd HH:mm:ss)
(15) Age calculation method, getAge*, such as getAge(Date birthday), calculates age by birthday.
(16) Method for determining whether the birthday is here, isBirthDay*, for example, isBirthDay (Date birthday), determine whether the current date is here based on the birthday.
(17) How to calculate the number of weeks, weekof*, such as weekOfMonth(Date date), which week of the month the date is.
(18) Determine whether Monday and Friday method, isMonday*, isZhouYi*, such as isZhouYi(Date date), isMonday.
(19) The twelve hours calculation method, getTwelveTwo*, such as getTwelveTwo(Date date), get the twelve hours corresponding to the specified time.
(20) Quarter calculation method, getQuarter*, such as getQuarter(Date date), get the quarter corresponding to the specified time.
(21) Get the accurate starting time method for 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 year, startTimeOfYear, such as startTimeOfYear(int year), get the start time of the specified year.
(23) Commonly used time (tomorrow, next week, next month, next year, etc.) calculation methods, such as tomorrow(), calculate tomorrow, and return Date.
(24) Modify the week value method withDayOfWeek*, such as withDayOfWeek(Date date, long newValue), modify the week to the specified value newValue, and return Date.
(25) Chinese working day calculation (including holiday information), including methods such as determining whether the current date is a working day and the next working day, isChineseWorkDay*, nextChineseWorkDay*,
For example, isChineseWorkDay(Date, String holidayData), nextChineseWorkDay(Date date, String holidayData),
Holiday Data, if the holiday data does not support the year, it will be judged from Monday to Friday as working days. Below is the holiday information I compiled for 2021:
2021-01-01:0,2021-02-07:1,2021-02-11:0,2021-02-12:0,2021-02-15:0,2021-02-16:0,2021-02-17:0,2021-02-20:1,2021-04-05:0,2021-04-25:1,2021-05-03:0,2021-05-04:0,2021-0 5-05:0,2021-05-08:1,2021-06-14:0,2021-09-18:1,2021-09-20:0,2021-09-21:0,2021-09-26:1,2021-10-01:0,2021-10-04:0,2021-10-05:0,2021-10-06:0,2021-10-07:0,2021-10-09:1
(26) Determine whether there is overlap (intersection) method for 2 or more time periods, isOverlap*, such as isOverlap(Date startDate1, Date endDate1, Date startDate2, Date endDate2), overlap returns true.
(27) Method for calculating the average time, averageTime*, such as averageTime(List dateList), returns the average time, such as "15:03:03".
(28) Calculate the countdown method based on the millisecond value, supports the incoming time objects and specified formats, countdown*, such as countdown(long millis), and returns the countdown, such as "27 hours, 10 minutes, 30 seconds".
(29) Get the formatting time list method for the specified interval, such as getDateFormatList(Date start, Date end, String dateFormatPattern) supports passing in formatting templates.
(30) Calculate the overlap (intersection) time method of 2 time periods, such as overlapTime(Date startDate1, Date endDate1, Date startDate2, Date endDate2), and returns the millisecond value.
For detailed use, you can view the relevant test code: DateTimeCalculatorUtilTest.
Contains 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.SSSSSSSSS
yyyy-MM-dd HH:mm:ss.SSSSSSSSSSSSS
yyyy-MM-dd'T'HH:mm:ssZ, etc., supports precise times such as milliseconds, microseconds and nanoseconds.
(1) Format method, format*, such as formatToDateStr(Date date), returns the date part, such as: yyyy-MM-dd;
format(Date date, DateTimeFormatter formatter) formatter You can select a defined formatter such as YYYY_MM_DD_HH_MM_SS_FMT (yyyy-MM-dd HH:mm:ss) formatting date.
(2) Analytical method, parse*, such as parseDateStrToDate(String text) parse the date yyyy-MM-dd, returning Date;
parseToDate(String text, DateTimeFormatter formatter) parse to Date according to formatter.
(3) Automatic parsing method, automatically recognize and parse according to the characteristics of the string, smartParse*, such as smartParseToDate(String text) automatically parses Date.
(4) Automatic parsing method for ISO format (including T) is automatically recognized and parsed according to the characteristics of the string. parseIso*, such as parseIsoToDate(String text) automatically parses Date.
(5) Parsing timestamp method, parseEpochMilli*, such as parseEpochMilliToDate(String text), parsing timestamp is Date, such as 1590224790000.
(6) parse the default format of Date, parseDateDefaultStr*, such as parseDateDefaultStrToDate(String text)
Analyze 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) Customize the template formatting method, 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.ffffffffffff where ffffffff nanoseconds, omit the following 0) formatting method.
For example formatTimestampStyle(Date date).
(11) Timestamp default format (yyyy-mm-dd hh:mm:ss.ffffffffffff where ffffffff is nanoseconds, omitting the following 0).
For example, parseTimestampStyleToDate(String text).
(12) Methods to verify whether the date format is correct, isValidDate*, such as isValidDate(String text), 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, and as long as one of the parsing is successful, the corresponding Date will be returned.
(14) Analyze 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, Map<String, String> naturalLanguageMap) supports custom parsing natural language time maps.
(15) Chinese date formatting methods, such as formatToChineseDateStr(Date date, boolean isUpperCase), isUpperCase false: September 11, 2021 true: September 11, 2021.
(16) Chinese date analysis methods, such as parseChineseDateStrToDate(String text), support: September 11, 2021 and September 11, 2021 format date analysis.
Note: When formatting and parsing different times from the system time zone, use a custom time zone formatting method, or you can 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: DateTimeFormatterUtilTest.
include:
(1) Generate a calendar for the specified time (calendar containing the hierarchy of year, month and day). GenerateCalendar* For example, generateCalendar(int year, int month) generates a calendar for the specified year and month.
(2) Generate a calendar of the specified time (calendar containing the hierarchy of year, month and day), including the lunar calendar and all holiday information methods, generateCalendarWithHoliday*, generateCalendarWithHoliday(int year, int month, Map<String, String> localHolidayMap, Map<String, String> chineseHolidayMap, Map<String, Integer> dateTypeMap) generates a calendar of the specified year and month, including the lunar calendar and all holiday information, and can customize holidays and working days, etc.
For detailed use, you can view the relevant test code: CalendarUtilTest.
Include:
(1) Calculation of lunar date, year, month and day.
(2) Calculate the zodiac signs during the lunar calendar.
(3) Calculation of the twenty-four solar terms, etc. (4) Notes on the lunar calendar to the Gregorian calendar: Only the lunar calendar conversion in the 1900-2100 Gregorian calendar is supported.
For detailed use, you can view the relevant test code: LunarDateTest.
Include:
(1) Calculate the Gregorian holidays, getLocalHoliday* For example, getLocalHoliday(Date date) calculates the Gregorian holidays of date, getLocalHoliday(Date date, Map<String, String> localHolidayMap) can pass in custom Gregorian holiday data.
(2) Calculation of lunar holidays, getChineseHoliday* For example, getChineseHoliday(Date date) calculates the lunar holiday of date, getChineseHoliday(Date date, Map<String, String> chineseHolidayMap) can pass in custom lunar holiday data.
(3) Calculation of the twenty-four solar terms, getSolarTerm* For example, getSolarTerm(Date date) calculates the twenty-four solar terms of date.
Note: LunarDate is used in the lunar calendar and the twenty-four solar terms, and only supports the calculations of the 1900-2100 years of the Gregorian calendar.
You can view the relevant test codes for detailed use.
cron expression 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 (integer of 1-7 or SUN-SAT (1=SUN)) year (optional, 1970-2099)
Special characters can be used for all fields:, - * / are enumeration, range, arbitrary, interval dates, and other:? LW is any, last, valid working day (Monday to Friday)
You can also use the week:? L # is any, and finally, the cron expression is commonly used in the week of each month:
(1)0 0 2 1 * ? * Indicates triggering at 2 am on the 1st of the month (2) 0 15 10 ? * MON-FRI indicates that the assignment is performed at 10:15 am on Monday to Friday (3) 0 15 10 ? * 6L 2002-2006 indicates that the assignment is performed at 10:15 am on the last Friday of each month from 2002-2006 (4) 0 0/30 9-17 * * ? Indicates every half hour (5) 0 15 10 L * ? Indicates triggering at 10:15 am on the last day of each month (6) 0 15 10 ? * 6#3 Indicates triggering at 10:15 am on the third Friday of each month (6) 0 15 10 ? * 6#3 Indicates triggering at 10:15 am on the third Friday of each month (4) 0 0/30 9-17 * * ? Indicates every half hour (5) 0 15 10 L * ? Indicates triggering at 10:15 am on the last day of each month (6) 0 15 10 ? * 6#3 Indicates triggering at 10:15 am on the third Friday of each month (6) 0 15 10 ? * 6#3 Indicates triggering at 10:15 am on the third Friday of each month (6) 0 15 10 ? *
Contains (1) validation and formatting Cron expression methods, isValidExpression and formatExpression.
(2) Generate the next or more execution time methods, getNextTime and getNextTimeList.
(3) Generate the date formatting (yyyy-MM-dd HH:mm:ss) method of the next execution time, getNextTimeStr and getNextTimeStrList.
(4) Compare whether the next execution time of the Cron expression is equal to the specified date method, isSatisfiedBy.
Note: The underlying layer uses quartz's CronExpression processing.
For detailed use, you can view the relevant test code: CronExpressionUtilTest.
Computing time-consuming tool, supports seconds, milliseconds, nanoseconds
include:
(1) Calculation takes time and returns time-consuming results.
(2) Calculation takes time, customize the task name, and output time-consuming results.
(3) Calculation time, return accurate timing, with 3 decimals, use ROUND_DOWN to discard the decimal parts that exceed 3 digits, etc.
For detailed use, you can view the relevant test code: CostUitlTest.
Includes functions:
(1) Analyze the natural language of time based on the current time.
(2) Analyze the natural language of time based on the specified time.
(3) Add a variety of calling methods, such as parseConcurrent concurrent execution, which can set timeout time and custom thread pool to improve execution efficiency.
Modified from https://github.com/shinyke/Time-NLP
Some modifications have been made as follows:
(1) Encapsulate the attributes and rename them to comply with camel naming standards.
(2) Change the loading regular resource file to singleton loading.
(3) Re-dividing classes into separate classes according to their functions.
(4) Rewrite using Java 8 date API.
(5) Add comments and optimize code.
(6) Repair the issue in the original project: standard time yyyy-MM-dd, yyyy-MM-dd HH:mm:ss and yyyy-MM-dd HH:mm analysis problems.
(7) Fix the issue in the original project: 1 hour, 1 and a half hours, 1 hour and 50 minutes and other analysis problems; and support it to seconds, such as 50 seconds, 10 minutes and 30 seconds.
(8) Repair the issue in the original project: The current time for repair is 10 am, so three pm will be identified as the problem of three pm tomorrow.
(9) Fix issue in the original project: Fix the decimal resolution exception problem.
(10) Performance optimization, precompile the used regularities and put them into the cache, and use them directly next time to improve performance.
Note: NLP will have a certain recognition failure rate, and it will continue to iterate and improve the success rate.
This feature is not included in the Mini version.
For detailed use, you can view the relevant test code: TimeNLPUtilTest.
Time unit constants, which facilitate calculation of unit conversion, such as setting cache time for 3 days: 3*MILLISECONDS_PER_DAY (24*60*60*1000 milliseconds per day)
Include:
(1) Convert the value of the basic unit, such as MILLISECONDS_PER_SECONDS 1000 milliseconds per second.
(2) Convert to the basic value of seconds, such as SECONDS_PER_DAY The number of seconds per day is 24*60*60.
(3) Convert to the basic value of milliseconds, such as MILLISECONDS_PER_DAY. The number of milliseconds per day is 24*60*60*1000.
For detailed use, you can view the relevant test code: XkTimeConstantTest.
(1) Fork project.
(2) Modify in the dev branch.
(3) Submit pull request.
(1) Common holidays, such as New Year's Day, Spring Festival, Qingming Festival, Labor Day, Dragon Boat Festival, Mid-Autumn Festival and other holidays.
(2) Supported by the 24 solar terms.