java 如何格式化日期/时间字符串?(爪哇)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38436916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:23:55  来源:igfitidea点击:

How to format date/time string? (Java)

javaparsingcalendar

提问by Wil Ferraciolli

Hi can anyone help please? I am trying to format a date and time string. Currently it looks like this "20160112T110000Z" and I need it to be "2016-01-12T11:00:00Z"

嗨,有人可以帮忙吗?我正在尝试格式化日期和时间字符串。目前它看起来像这样“ 20160112T110000Z”,我需要它是“ 2016-01-12T11:00:00Z

The string without the special characters are returned from a 3rd party recurrence library. I need to convert it to have the special characters before parsing it to a Calendarobject.

没有特殊字符的字符串从第 3 方重复库返回。在将其解析为Calendar对象之前,我需要将其转换为具有特殊字符。

Can anyone help please?

有人可以帮忙吗?

The code that I have so far looks like:

到目前为止,我的代码如下所示:

 final String TIMEFORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
 String string = "20160112T110000Z";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = format.parse(string);
    System.out.println(date); 

However this just does not work.

然而,这只是行不通。

Any suggestions are appreciated

任何建议表示赞赏

回答by Arnaud

You have to read the string with a format matching the source, this gives you a correct Date.

您必须使用与源匹配的格式读取字符串,这将为您提供正确的Date.

Then simply write it with the format you want :

然后简单地用你想要的格式写它:

    String string = "20160112T110000Z";

    String originalStringFormat = "yyyyMMdd'T'HHmmss'Z'";
    String desiredStringFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    SimpleDateFormat readingFormat = new SimpleDateFormat(originalStringFormat);
    SimpleDateFormat outputFormat = new SimpleDateFormat(desiredStringFormat);

    try {
        Date date = readingFormat.parse(string);
        System.out.println(outputFormat.format(date));
    } catch (ParseException e) {

        e.printStackTrace();
    }