티스토리 뷰
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* This pattern has the following benefits:
*
* - Date formats are referenced as a strong type
* - Code completion on patterns
* - Patterns can be javadoc'ed
*/
public enum Dates {
/**
* <p>Format: yyyy-MM-dd</p>
* <p>Example: 2022-03-30</p>
*/
yyyy_MM_dd("yyyy-MM-dd"),
/**
* <p>Format: MMM dd, yyyy</p>
* <p>Example: Mar 30, 2022</p>
*/
MMM_dd_yyyy("MMM dd, yyyy");
private final DateTimeFormatter formatter;
Dates(final String formatString) {
formatter = DateTimeFormatter.ofPattern(formatString);
}
public LocalDate parse(final String string) {
return LocalDate.parse(string, formatter);
}
public String format(final LocalDate date) {
return formatter.format(date);
}
public Date parseDate(final String string) {
return Date.from(parse(string).atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
}
public String format(final Date date) {
return format(date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDate());
}
}
출처: https://gist.github.com/dblevins/47f7508e241d775fd7007a4639d6565a
댓글