Java 将日期字符串转换为不同的格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6637469/
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
Converting date-string to a different format
提问by lobner
I have a string containing a date in the format YYYY-MM-DD
.
我有一个包含格式的日期的字符串YYYY-MM-DD
。
How would you suggest I go about converting it to the format DD-MM-YYYY
in the best possible way?
您如何建议我以DD-MM-YYYY
最佳方式将其转换为格式?
This is how I would do it naively:
这就是我天真地做的方式:
import java.util.*;
public class test {
public static void main(String[] args) {
String date = (String) args[0];
System.out.println(date); //outputs: YYYY-MM-DD
System.out.println(doConvert(date)); //outputs: DD-MM-YYYY
}
public static String doConvert(String d) {
String dateRev = "";
String[] dateArr = d.split("-");
for(int i=dateArr.length-1 ; i>=0 ; i--) {
if(i!=dateArr.length-1)
dateRev += "-";
dateRev += dateArr[i];
}
return dateRev;
}
}
But are there any other, more elegant AND effective way of doing it? Ie. using some built-in feature? I have not been able to find one, while quickly searching the API.
但是还有其他更优雅、更有效的方法吗?IE。使用一些内置功能?我一直没能找到一个,同时快速搜索 API。
Anyone here know an alternative way?
这里有人知道另一种方法吗?
采纳答案by duffymo
Use java.util.DateFormat
:
使用java.util.DateFormat
:
DateFormat fromFormat = new SimpleDateFormat("yyyy-MM-dd");
fromFormat.setLenient(false);
DateFormat toFormat = new SimpleDateFormat("dd-MM-yyyy");
toFormat.setLenient(false);
String dateStr = "2011-07-09";
Date date = fromFormat.parse(dateStr);
System.out.println(toFormat.format(date));
回答by Hovercraft Full Of Eels
Best to use a SimpleDateFormat (API) object to convert the String to a Date object. You can then convert via another SimpleDateFormat object to whatever String representation you wish giving you tremendous flexibility.
最好使用 SimpleDateFormat ( API) 对象将 String 转换为 Date 对象。然后,您可以通过另一个 SimpleDateFormat 对象转换为您希望为您提供极大灵活性的任何字符串表示形式。
回答by JB Nizet
If you're not looking for String to Date conversion and vice-versa, and thus don't need to handle invalid dates or anything, String manipulation is the easiest and most efficient way. But i's much less readable and maintainable than using DateFormat.
如果您不寻找字符串到日期的转换,反之亦然,因此不需要处理无效日期或任何事情,字符串操作是最简单和最有效的方法。但与使用 DateFormat 相比,我的可读性和可维护性要差得多。
String dateInNewFormat = dateInOldFormat.substring(8)
+ dateInOldFormat.substring(4, 8)
+ dateInOldFormat.substring(0, 4)
回答by Krunal
import java.util.DateFormat;
// Convert String Date To Another String Date
public String convertStringDateToAnotherStringDate(String stringdate, String stringdateformat, String returndateformat){
try {
Date date = new SimpleDateFormat(stringdateformat).parse(stringdate);
String returndate = new SimpleDateFormat(returndateformat).format(date);
return returndate;
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
//-------
String resultDate = convertStringDateToAnotherStringDate("1997-01-20", "yyyy-MM-dd", "MM/dd/yyyy")
System.out.println(resultDate);
Result (date string) : 01/20/1997
结果(日期字符串):01/20/1997
回答by Ole V.V.
Here's the modern answer.
这是现代答案。
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu");
public static String doConvert(String d) {
return LocalDate.parse(d).format(formatter);
}
With this we may do for example:
有了这个,我们可以做例如:
System.out.println(doConvert("2017-06-30"));
This prints
这打印
30-06-2017
I am exploiting the fact that the format you have, YYYY-MM-DD
, conforms with the ISO 8601 standard, a standard that the modern Java date and time classes “understand” natively, so we need no explicit formatter for parsing, only one for formatting.
我正在利用这样一个事实,即您拥有的格式YYYY-MM-DD
符合 ISO 8601 标准,这是现代 Java 日期和时间类本机“理解”的标准,因此我们不需要显式格式化程序来解析,只需要一个格式化程序。
When this question was asked in 2011, SimpleDateFormat
was also the answer I would have given. The newer date and time API came out with Java 8 early in 2014 and has also been backported to Java 6 and 7 in the ThreeTen-Backport project. For Android, see the ThreeTenABP project. So these days honestly I see no excuse for still using SimpleDateFormat
and Date
. The newer classes are much more programmer friendly and nice to work with.
当这个问题在 2011 年被问到时,SimpleDateFormat
这也是我会给出的答案。较新的日期和时间 API 于 2014 年初随 Java 8 发布,并且在 ThreeTen-Backport 项目中也已向后移植到 Java 6 和 7。对于 Android,请参阅 ThreeTenABP 项目。所以这些天老实说,我认为没有理由继续使用SimpleDateFormat
和Date
。较新的类对程序员更加友好,并且易于使用。