【Java】字符串轉換日期

str->Date

 //str->Date
    public static Date strToDate(String dateTimeStr,String formatStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
//        System.out.println(dateTimeFormatter);//org.joda.time.format.DateTimeFormatter@4e515669
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }

date->str

//date ->str
    public static String dateToStr(Date date,String formatStr){
        if(date == null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(formatStr);
    }

DateTimeUtil

public class DateTimeUtil {

    //joda-time

    //str->Date
    //Date->str

    //standard_format
    public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";


    //str->Date
    public static Date strToDate(String dateTimeStr,String formatStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
//        System.out.println(dateTimeFormatter);//org.joda.time.format.DateTimeFormatter@4e515669
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }
    //str ->date
    public static Date strToDate(String dateTimeStr){
        DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
        DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
        return dateTime.toDate();
    }

    //date ->str
    public static String dateToStr(Date date,String formatStr){
        if(date == null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(formatStr);
    }

    //date ->str
    public static String dateToStr(Date date){
        if(date == null){
            return StringUtils.EMPTY;
        }
        DateTime dateTime = new DateTime(date);
        return dateTime.toString(STANDARD_FORMAT);
    }




    public static void main(String[] args) {
        System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
        System.out.println(DateTimeUtil.dateToStr(new Date(),STANDARD_FORMAT));
        System.out.println(DateTimeUtil.dateToStr(new Date()));
        System.out.println(DateTimeUtil.strToDate("1111-11-11 11:11:11","yyyy-MM-dd HH:mm:ss"));
        System.out.println(DateTimeUtil.strToDate("1111-11-11 11:11:11",STANDARD_FORMAT));
        System.out.println("1111-11-11 11:11:11");
        //eg:
        //2020-06-05 11:20:49
        //2020-06-05 11:20:49
        //Sat Nov 04 11:05:14 CST 1111
        //Sat Nov 04 11:05:14 CST 1111
    }


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章