Java如何实现字符串和Date类型之间转换呢?
下文笔者讲述字符串和Date之间互相转换的方法分享,如下所示
字符串和Date之间互相转换 1.定义一个SimpleDateFormat对象 2.使用simpleDateFormat对象中的方法进行字符串和Date之间互相转换例
1.将字符串转换成Date类型
//字符串转Date类型 String time = "2023-05-24 09:12:22"; 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);//2023-05-24 09:12:22 SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日"); Date date = new Date(); String nowTime = format.format(date); System.out.println("当前的时间::"+nowTime);//2023年05月24日 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秒
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。