java怎么把“20230820”解析成为"yyyy-MM-dd"格式

动态 未结 0 120
小小草
小小草 LV1 2023年9月23日 23:40 发表
在Java中,可以使用SimpleDateFormat类将日期字符串解析为指定格式的日期。要将"20230820"解析为"yyyy-MM-dd"格式,可以按照以下步骤进行: 1. 创建一个SimpleDateFormat对象,并设置其日期格式为"yyyyMMdd"。 ``` SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); ``` 2. 调用SimpleDateFormat对象的parse()方法,将日期字符串解析为Date对象。 ``` Date date = sdf.parse("20230820"); ``` 3. 创建一个新的SimpleDateFormat对象,并设置其日期格式为"yyyy-MM-dd"。 ``` SimpleDateFormat newSdf = new SimpleDateFormat("yyyy-MM-dd"); ``` 4. 调用新的SimpleDateFormat对象的format()方法,将Date对象格式化为"yyyy-MM-dd"格式的日期字符串。 ``` String formattedDate = newSdf.format(date); ``` 完整代码如下: ``` SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); Date date = sdf.parse("20230820"); SimpleDateFormat newSdf = new SimpleDateFormat("yyyy-MM-dd"); String formattedDate = newSdf.format(date); System.out.println(formattedDate); // 输出:2023-08-20 ``` 注意,在解析日期字符串时,可能会抛出ParseException异常,需要进行异常处理。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复