【问题标题】:Format date in Java在 Java 中格式化日期
【发布时间】:2010-11-14 11:40:55
【问题描述】:

我有以下字符串:

Mon Sep 14 15:24:40 UTC 2009

我需要把它格式化成这样的字符串:

14/9/2009

我如何在 Java 中做到这一点?

【问题讨论】:

    标签: java date-format


    【解决方案1】:

    使用SimpleDateFormat(单击javadoc 链接查看模式)将一种模式中的字符串解析为完全值得的Date,并使用另一种模式将解析后的Date 格式化为另一种模式中的字符串。

    String string1 = "Mon Sep 14 15:24:40 UTC 2009";
    Date date = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy").parse(string1);
    String string2 = new SimpleDateFormat("d/M/yyyy").format(date);
    System.out.println(string2); // 14/9/2009
    

    【讨论】:

      【解决方案2】:

      您可以使用 SimpleDateFormat 类将您拥有的字符串转换为日期对象。日期格式可以在构造函数中给出。 format 方法将字符串转换为日期对象。

      获取到日期对象后,可以按照自己想要的方式进行格式化。

      【讨论】:

      • 我试过了: SimpleDateFormat sdfIn = new SimpleDateFormat("Mon Sep 14 15:24:40 UTC 2009");但它没有用!我得到:线程“main”中的异常 java.lang.IllegalArgumentException:非法模式字符 'o'
      • 您需要使用本页表格中显示的模式:download.oracle.com/javase/1.4.2/docs/api/java/text/…
      【解决方案3】:

      java 8 及更高版本中的一个衬里。

      String localDateTime= LocalDateTime.parse("Mon Sep 14 15:24:40 UTC 2009", DateTimeFormatter.ofPattern("EE MMM dd HH:mm:ss z yyyy")).format(DateTimeFormatter.ofPattern("d/M/yyyy"));
      

      【讨论】:

        【解决方案4】:
        Date d = new Date("Mon Sep 14 15:24:40 UTC 2009");
        SimpleDateFormat f = new SimpleDateFormat("dd/M/yyyy");
        String s = new String(f.format(d));
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多