【问题标题】:Taking a String that is a Date and Formatting it in Java获取作为日期的字符串并在 Java 中对其进行格式化
【发布时间】:2012-11-03 07:52:07
【问题描述】:

我在 Java 中有一个字符串,它是一个日期,但格式如下:

02122012

我需要重新格式化它,使其看起来像 2012 年 2 月 12 日 怎么做。

使用以下代码,我不断返回 java.text.SimpleDateFormat@d936eac0

下面是我的代码..

public static void main(String[] args) {

    // Make a String that has a date in it, with MEDIUM date format
    // and SHORT time format.
    String dateString = "02152012";

    SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
    SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
    try {
        output.format(input.parse(dateString));
    } catch (Exception e) {

    }
    System.out.println(output.toString());
}

【问题讨论】:

  • 同意亚历克斯,即使这意味着 02122012,你有什么尝试?
  • @BlueBullet:您已经编辑了原始问题假设,这只是一个错字。我宁愿从 OP 那里听到。
  • 我不断返回 java.text.SimpleDateFormat@d936eac0

标签: java date format


【解决方案1】:

使用 SimpleDateFormat。

SimpleDateFormat input = new SimpleDateFormat("ddMMyyyy");
SimpleDateFormat output = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012

按照 Jon Skeet 的建议,您还可以在 SimpleDateFormat 上设置 TimeZoneLocale

SimpleDateFormat englishUtcDateFormat(String format) {
    SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    return sdf;
}

SimpleDateFormat input = englishUtcDateFormat("ddMMyyyy");
SimpleDateFormat output = englishUtcDateFormat("dd/MM/yyyy");
System.out.println(output.format(input.parse("02122012"))); // 02/12/2012

【讨论】:

  • 我建议将时区指定为 UTC,将语言环境指定为英语,甚至还可以明确设置日历。
  • 它不起作用...如果我执行 output.toString(),我得到 java.text.SimpleDateFormat@d936eac0
  • @techsjs2012:请参阅我的回答,了解您在编辑中做错了什么。
【解决方案2】:

这是您编辑问题中代码的问题:

System.out.println(output.toString());

您打印的是SimpleDateFormat,而不是调用format 的结果。事实上,您忽略调用format 的结果:

output.format(input.parse(dateString));

只需将其更改为:

System.out.println(output.format(input.parse(dateString)));

或者更清楚:

Date parsedDate = input.parse(dateString);
String reformattedDate = output.format(parsedDate);
System.out.println(reformattedDate);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2013-01-05
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多