DateHelper Tutorial
This tutorial provides an overview of the DateHelper class, which is part of the lightweight-component/aj-util library. The DateHelper class provides utility methods for working with dates and times in Java applications.
Introduction
The DateHelper class contains static methods for common date/time operations using Java 8's java.time API, including formatting, parsing, and conversion between different date/time types.
Main Features
- Thread-safe date/time formatting and parsing
- Conversion between legacy Date and java.time types
- Support for multiple standard date/time formats
- RFC1123 and ISO8601 timestamp generation
- Object to date conversion utilities
Standard Formats
TIME- "HH:mm:ss"DATETIME- "yyyy-MM-dd HH:mm:ss"DATETIME_SHORT- "yyyy-MM-dd HH:mm"DATE- "yyyy-MM-dd"
Methods
1. Formatting Methods
formatDate(LocalDate date)- Format LocalDate to stringformatTime(LocalTime time)- Format LocalTime to stringformatDateTime(LocalDateTime dateTime)- Format LocalDateTime to stringformatDateTime(Date dateTime)- Format Date to string
2. Parsing Methods
parseDate(String dateStr)- Parse string to LocalDateparseTime(String timeStr)- Parse string to LocalTimeparseDateTime(String dateTimeStr)- Parse string to LocalDateTimeparseDateTimeShort(String dateTimeStr)- Parse short format string to LocalDateTime
3. Type Conversion
localDateTime2Date(LocalDateTime localDateTime)- Convert LocalDateTime to DatelocalDate2Date(LocalDate localDate)- Convert LocalDate to DatetoLocalDate(Date date)- Convert Date to LocalDatetoLocalDateTime(Date date)- Convert Date to LocalDateTime
4. Standard Timestamps
getGMTDate()- Get current time in RFC1123 formatgetISO8601Date()- Get current time in ISO8601 format
5. Utility Methods
object2Date(Object obj)- Convert various object types to DatenowDateTime()- Get current Datenow()- Get current time as formatted stringnow(String format)- Get current time with custom formatnowShort()- Get current time in short format
Usage Examples
Formatting Dates
LocalDateTime now = LocalDateTime.now();
String formatted = DateHelper.formatDateTime(now); // "2023-01-15 14:30:45"
Parsing Dates
LocalDate date = DateHelper.parseDate("2023-01-15");
LocalDateTime dateTime = DateHelper.parseDateTime("2023-01-15 14:30:45");
Type Conversion
Date date = new Date();
LocalDateTime ldt = DateHelper.toLocalDateTime(date);
Date newDate = DateHelper.localDateTime2Date(ldt);
Standard Timestamps
String rfc1123 = DateHelper.getGMTDate(); // "Mon, 15 Jan 2023 14:30:45 GMT"
String iso8601 = DateHelper.getISO8601Date(); // "2023-01-15T14:30:45Z"
Object Conversion
Date fromLong = DateHelper.object2Date(1673793045000L);
Date fromString = DateHelper.object2Date("2023-01-15");
Date fromLocal = DateHelper.object2Date(LocalDateTime.now());
Conclusion
The DateHelper class provides comprehensive utility methods for working with dates and times, making it easier to format, parse, and convert between different date/time representations in Java applications.