字符串与Date类型相互转换

1、将字符串转换成Date类型

		//字符串转Date类型
        String time = "2020-02-02 02:02:02";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date newTime = format.parse(time);
            System.out.println("转换以后的时间::"+newTime);//Sun Feb 02 02:02:02 CST 2020
        } catch (ParseException e) {
            e.printStackTrace();
        }

2、将Date类型转换成字符串

		//Date类型转换成字符串
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String nowTime = format.format(date);
        System.out.println("当前的时间::"+nowTime);//2020-08-25 21:28:22

		SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
		Date date = new Date();
        String nowTime = format.format(date);
        System.out.println("当前的时间::"+nowTime);//2020年08月25日
        
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        Date date = new Date();
        String nowTime = format.format(date);
        System.out.println("当前的时间::"+nowTime);//2020年08月25日21时41分09秒

你可能感兴趣的:(java工具类,java)