java8 时间工具类

2019-01-19 17:07:16 669

自己写的java8时间类的工具类

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.Temporal;

public class DateUtils {

    private static final String DEAFAULT_DATA_PATTERN="yyyy-MM-dd";
    private static final String DEAFAULT_TIME_PATTERN="HH:mm:ss";
    private static final String DEAFAULT_DATATIME_PATTERN="yyyy-MM-dd HH:mm:ss";

    /** String ---> LocalDate */
    public static LocalDate parseToLocalDate(String dateStr){
        LocalDate localDate=parseToLocalDate(dateStr, DEAFAULT_DATA_PATTERN);
        return localDate;
    }

    public static LocalDate parseToLocalDate(String dateStr,String pattern){
        LocalDate localDate=LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(pattern));
        return localDate;
    }

    /** String ---> LocalDateTime */
    public static LocalDateTime parseToLocalDateTime(String dateTimeStr){
        LocalDateTime localDatetime=parseToLocalDateTime(dateTimeStr,DEAFAULT_DATATIME_PATTERN);
        return localDatetime;
    }

    public static LocalDateTime parseToLocalDateTime(String dateTimeStr,String pattern){
        LocalDateTime localDatetime=LocalDateTime.parse(dateTimeStr, DateTimeFormatter.ofPattern(pattern));
        return localDatetime;
    }

    /** String ---> LocalTime */
    public static LocalTime parseToLocalTime(String timeStr){
        LocalTime localTime=parseToLocalTime(timeStr, DEAFAULT_TIME_PATTERN);
        return localTime;
    }

    public static LocalTime parseToLocalTime(String timeStr,String pattern){
        LocalTime localTime=LocalTime.parse(timeStr, DateTimeFormatter.ofPattern(pattern));
        return localTime;
    }

    /** LocalTime / LocalDate / LocalDateTime ---> String */
    public static String formatToString(Temporal temporal,String pattern){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        String temporalStr=df.format(temporal);
        return temporalStr;
    }

    /**  LocalDate / LocalDateTime ---> String("yyyy-MM-dd") */
    public static String formatLoalDate(Temporal temporal){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DEAFAULT_DATA_PATTERN);
        String temporalStr=df.format(temporal);
        return temporalStr;
    }

    /** LocalTime / LocalDateTime ---> String ("HH:mm:ss") */
    public static String formatLoalTime(Temporal temporal){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DEAFAULT_TIME_PATTERN);
        String temporalStr=df.format(temporal);
        return temporalStr;
    }

    /** LocalDate / LocalDateTime ---> String ("yyyy-MM-dd HH:mm:ss")*/
    public static String formatLoalDateTime(Temporal temporal){
        DateTimeFormatter df = DateTimeFormatter.ofPattern(DEAFAULT_DATATIME_PATTERN);
        String temporalStr=df.format(temporal);
        return temporalStr;
    }
}

java string static class pattern parse

作者

天空的星星
TA的文章

相关文章