使用format()方法将日期转换为字符串或字符串转换日期

package com.zwwhnly.springbootdemo;
import java.text.SimpleDateFormat;
import java.util.Date;
public class SimpleDateFormatDemo {
    public static void main(String[] args) {
        Date currentTime = new Date();
        System.out.println(currentTime);    // Mon Feb 18 13:53:50 CST 2019

      SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat("yyyy/MM/dd");
        System.out.println(simpleDateFormat1.format(currentTime));  // 输出2019-02-18 13:53:50.629
        System.out.println(simpleDateFormat2.format(currentTime));  // 输出2019-02-18
        System.out.println(simpleDateFormat3.format(currentTime));  // 输出2019/02/18
    }
}

字符串转换日期:

public class SimpleDateFormatDemo {
    public static void main(String[] args) {
        try {

           //首先定义格式
            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String strDate1 = "2019-02-18 13:58";

            //按格式进行转换
            Date date1 = simpleDateFormat1.parse(strDate1);
            System.out.println(date1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

 

posted on 2019-02-21 10:13  城市小农民  阅读(504)  评论(0编辑  收藏  举报

导航