Java 8 Time API处理日期和时间

日期解析、转化为时间戳等

/**
 * @author coder4
 */
public class DayUtils {

    private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * Parse epoch seconds to LocalDate
     *
     * @param epochSecs
     * @return
     */
    public static LocalDate parse(long epochSecs) {
        return Instant.ofEpochMilli(epochSecs).atZone(ZoneId.systemDefault()).toLocalDate();
    }

    /**
     * Parse day to LocalDate
     *
     * @param day e.g. 20171010
     * @return
     */
    public static LocalDate parse(int day) {
        return LocalDate.parse(Integer.toString(day), DTF);
    }

    /**
     * Convert LocalDate to million-seconds
     *
     * @param date
     * @return e.g. 20171010
     */
    private static int format(LocalDate date) {
        return Integer.parseInt(DTF.format(date));
    }

    /**
     * get epoch million-seconds from day
     *
     * @param day e.g. 20171010
     * @return ms from 1970
     */
    public static long getMillis(int day) {
        return parse(day).atStartOfDay(ZoneOffset.systemDefault()).toEpochSecond() * UnitUtils.SECOND;
    }

    /**
     * get next day of $day
     *
     * @param day e.g. 20171010
     * @return e.g. 20171011
     */
    public static int nextDay(int day) {
        return format(parse(day).plusDays(1));
    }

    /**
     * get prev day of $day
     *
     * @param day e.g. 20171010
     * @return e.g. 20171009
     */
    public static int prevDay(int day) {
        return format(parse(day).minusDays(1));
    }

}

 

Leave a Reply

Your email address will not be published.