String和Date转换

1.Date转String

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateTime = sdf.format(date);

2.String 转Date

        String dateTime = "2019-01-01 01:01:01";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }

加异常处理是因为String 的格式可能会和 SimpleDateFormat指定的格式不符合,比如String dateTime没有时分秒,或者少了年月日时分秒中的某一个,都会抛出ParseException异常

2021-05-24更新

     @Test
     public void Test2(){
         Date time =new Date("Tue Mar 26 00:00:00 CST 2019");
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         String timeFormat = sdf.format(time);
         System.out.println(timeFormat);
     }