Date与String的相互转换

Java时间转化类型

SimpleDateFormate的几种形式

 public static void main(String[] args) {
        SimpleDateFormat simpleDateFormat0 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd a E");
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a E");
        Date date = new Date() ;
        System.out.println(simpleDateFormat0.format(date));
        System.out.println(simpleDateFormat1.format(date));
        System.out.println(simpleDateFormat2.format(date));
    }

输出结果

2018-12-29
2018-12-29 上午 星期六
2018-12-29 11:08:53 上午 星期六

Date转换String类型

常用的转换方法:format方法

//	第一种参数为Date类型
Date date = new Date();
String date0 = simpleDateFormat0.format(date);
System.out.println(date0);
//第二种参数位Object类型
Date date = new Date();
Map<String, Object> map = new HashMap<String, Object>();
map.put("date", date);
String date1 = simpleDateFormat0.format(map.get("date"));
System.out.println(date1);

还有一种返回类型是StringBuffer的方法,感兴趣可以看一下jdk

String类型转换Date

常用的方法:simpleDateFormat的parse方法

Map<String, String> map = new HashMap<String, String>();
        map.put("date", "2018-12-29");
        Date date1 = null;
        try {
           date1 = simpleDateFormat0.parse(map.get("date"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(date1);

输出结果:

Sat Dec 29 00:00:00 CST 2018

猜你喜欢

转载自blog.csdn.net/V_YES_ME/article/details/85336832
今日推荐