博客
关于我
java 使用SimpleDateFormat类,把2018-03-04转换为2018年03月04日。
阅读量:617 次
发布时间:2019-03-13

本文共 932 字,大约阅读时间需要 3 分钟。

为了将日期字符串"2018-03-04"格式化为"2018年03月04日",我们可以使用SimpleDateFormat类进行解析和格式化操作。抽取要点如下:

  • 解析日期字符串

    • 使用SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    • 解析字符串"2018-03-04",将其转换为Date对象。
  • 格式化日期对象

    • 使用SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
    • 将Date对象格式化为目标日期字符串"2018年03月04日"。
  • 注意事项

    • 确保SimpleDateFormat对象使用中文环境,避免因为默认语言环境导致格式错误。
    • 具体实现代码如下:
  • import java.text.SimpleDateFormat;import java.util.Date;public class Test {    public static void main(String[] args) throws ParseException {        String strDate = "2018-03-04";                // 创建解析日期的SimpleDateFormat对象        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");        Date date = sdf1.parse(strDate);                // 创建格式化日期的SimpleDateFormat对象,并使用中文环境        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA);        strDate = sdf2.format(date);                System.out.println(strDate);    }}

    这个实现确保了日期正确转换,并考虑了环境设置,确保输出符合预期。

    转载地址:http://idtaz.baihongyu.com/

    你可能感兴趣的文章