티스토리 뷰

Java

Enum을 이용한 Date 포맷

Kaboomba 2022. 3. 13. 14:21
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

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/11   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
글 보관함