简体   繁体   English

java中日期字符串的特定日期格式

[英]Specific date format from date string in java

I have a date string which is 我有一个日期字符串

"20120514045300.0Z"

I'm trying to figure out how to convert this to the following format 我正在试图弄清楚如何将其转换为以下格式

"2012-05-14-T045300.0Z"

How do you suggest that I should solve it? 你怎么建议我解决它?

Instead of diving into hard-to-read string manipulation code, you should parse the date into a decent representation and from that representation format the output. 您应该将日期解析为适当的表示形式,并从该表示格式解析输出,而不是潜入难以阅读的字符串操作代码。 If possible, I would recommend you to stick with some existing API. 如果可能的话,我建议你坚持使用一些现有的API。

Here's a solution based on SimpleDateFormat . 这是基于SimpleDateFormat的解决方案。 (It hardcodes the 0Z part though.) (它虽然硬编码了0Z部分。)

String input = "20120514045300.0Z";

DateFormat inputDF  = new SimpleDateFormat("yyyyMMddHHmmss'.0Z'");
DateFormat outputDF = new SimpleDateFormat("yyyy-MM-dd'-T'HHmmss.'0Z'");

Date date = inputDF.parse(input);
String output = outputDF.format(date);

System.out.println(output);  // Prints 2012-05-14-T045300.0Z as expected.

(Adapted from here: How to get Date part from given String? .) (改编自: 如何从给定的字符串中获取日期部分?

You need to parse the date and them format it to desirable form. 您需要解析日期并将其格式化为所需的表单。 Use SimpleDateFormat to do it. 使用SimpleDateFormat来完成它。 You can also check out this question for more details. 您还可以查看问题以获取更多详细信息。

You don't necessarily have to use a DateFormat for something as simple as this. 您不必使用DateFormat来处理这么简单的事情。 You know what the format of the original date string is and you don't need a Date object, you want a String . 您知道原始日期字符串的格式是什么,并且您不需要Date对象,您需要一个String So simply transform it directly into a String (without creating an intermediary Date object) as follows: 因此,只需将其直接转换为String (不创建中间Date对象),如下所示:

String s = "20120514045300.0Z";
String formatted = s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8) + "-T" + s.substring(8);

You can even use StringBuilder as follows (although this is a bit inefficient due to array copying): 您甚至可以按如下方式使用StringBuilder (尽管由于数组复制,这有点效率低):

StringBuilder sb = new StringBuilder(s);
sb.insert(4, '-').insert(7,'-').insert(10,"-T");
String formatted = sb.toString();

If you just need to reformat the string, you could use something like so: 如果你只需要重新格式化字符串,你可以使用类似的东西:

String str = "20120514045300.0Z";
Pattern p = Pattern.compile("^(\\d{4})(\\d{2})(\\d{2})(.+)$");
Matcher m = p.matcher(str);
if (m.matches())
{
    String newStr = m.group(1) + "-" + m.group(2) + "-" + m.group(3) + "-T" + m.group(4);
    System.out.println(newStr);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM