简体   繁体   English

处理不同的字符串日期格式

[英]Dealing with different String date formats

In java, I have a string with a date in dd-mm-yyyy format: 在Java中,我有一个日期为dd-mm-yyyy的字符串:

String value = "31-01-1989";

Now, I want the value in another variable to be ddmmyyyy format: 现在,我希望另一个变量中的值为ddmmyyyy格式:

String value = "31011989";

How to do this? 这个怎么做?

In this case you can simply remove dashes 在这种情况下,您只需删除破折号

value = value.replace("-", "");

or 要么

value = value.replaceAll("-", "");

but according to my tests the first version is a little bit faster. 但是根据我的测试,第一个版本要快一些。 So I personally prefer to use replaceAll only when the first parameter is a regex. 因此,我个人更喜欢仅在第一个参数是正则表达式时才使用replaceAll。

Note that, despite a confusion in the names, String.replace replaces ALL substrings that match the first arg, just as String.replaceAll does. 请注意,尽管名称混乱,但String.replace替换与第一个arg匹配的所有子字符串,就像String.replaceAll一样。 The main difference is that the String.replace treats the first arg as a string literal and String.replaceAll uses it as a regex. 主要区别在于String.replace将第一个arg视为字符串文字,而String.replaceAll则将其用作正则表达式。

easy solution: 简单的解决方案:

String value1 = "31-01-1989";
String value2 = value1.replace("-", "");

Have a look at SimpleDateFormat for a general solution. 看看SimpleDateFormat作为一般解决方案。 Write a SimpleDateFormat to parse the first date and use format in another to have the expected output. 编写SimpleDateFormat解析第一个日期,并在另一个日期中使用format以获得预期的输出。

You can use String.replace(Charseq, Charseq) to remove the delimiters. 您可以使用String.replace(Charseq, Charseq)删除定界符。

String value = "31-01-1989";
String value2 = value.replace("-", "");
System.out.println(value2);

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

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