【问题标题】:How to convert date format in java?如何在java中转换日期格式?
【发布时间】:2012-02-13 03:51:37
【问题描述】:

我有一个字符串a ="   December 2011   "; 在它之前和之后都有一个 。 如何将其转换为:String b = "2011-12-1"

【问题讨论】:

  • 来吧,在发布问题之前,请至少在此网站上搜索

标签: java html date jsoup


【解决方案1】:

如果真的只有这些,请使用.replace()

String b = a.replace(" ", "");

不像它的名字会让你相信,因为.replaceAll() 存在,.replace() 实际上将替换 所有 次出现。不同之处在于.replaceAll() 需要一个字符串,该字符串将被编译为Pattern 作为参数。

【讨论】:

    【解决方案2】:

    使用SimpleDateFormat

    new SimpleDateFormat("yyyy-MM-d").format(new SimpleDateFormat("MMMMM yyyy").parse(str));

    【讨论】:

      【解决方案3】:
      String a = " Dezember 2011 ";
      SimpleDateFormat sdf = new SimpleDateFormat("MMMMM yyyy");
      
      a = a.replace(" ", "");
      
      Date parse = sdf.parse(a);
      SimpleDateFormat outSdf = new SimpleDateFormat("yyyy-MM-d");
      String out = outSdf.format(parse);
      System.out.println(out);
      

      【讨论】:

        【解决方案4】:

        您使用此代码。它提供您想要输出的任何内容。 您首先使用替换功能删除 &nbsp ,然后您必须解析您的字符串。

         try {
                        String a = " December 2011 ";
                        a = a.replace(" ", "");
                        SimpleDateFormat sdf = new SimpleDateFormat("MMMMM yyyy");
                        SimpleDateFormat SdfParser = new SimpleDateFormat("yyyy-MM-dd");
        
                        String date =SdfParser.format(sdf.parse(a)); 
                        System.out.println(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
        

        【讨论】:

          猜你喜欢
          • 2019-08-03
          • 1970-01-01
          • 1970-01-01
          • 2017-08-15
          • 2013-09-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多