将日期字符串转换为其他格式
我有一个字符串,其中包含YYYY-MM-DD
格式的日期。
您如何建议我以最佳方式将其转换为DD-MM-YYYY
格式?
这就是我天真的做法:
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; } }
但还有其他更优雅和有效的方法吗? IE浏览器。 使用一些内置function? 我一直无法找到一个,同时快速搜索API。
这里有人知道另一种方式吗?
使用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));
最好使用SimpleDateFormat( API )对象将String转换为Date对象。 然后,您可以通过另一个SimpleDateFormat对象转换为您希望的任何String表示,从而为您提供极大的灵活性。
如果您不是在寻找字符串到日期转换,反之亦然,因此不需要处理无效日期或任何事情,字符串操作是最简单和最有效的方法。 但是,与使用DateFormat相比,我的可读性和可维护性要低得多。
String dateInNewFormat = dateInOldFormat.substring(8) + dateInOldFormat.substring(4, 8) + dateInOldFormat.substring(0, 4)
这是现代的答案。
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-uuuu"); public static String doConvert(String d) { return LocalDate.parse(d).format(formatter); }
有了这个,我们可以这样做:
System.out.println(doConvert("2017-06-30"));
这打印
30-06-2017
我正在利用你所拥有的格式YYYY-MM-DD
这一事实符合ISO 8601标准,这是现代Java日期和时间类本身“理解”的标准,因此我们不需要明确的格式化器来解析,只有一个用于格式化。
当在2011年提出这个问题时, SimpleDateFormat
也是我给出的答案。 新的日期和时间API在2014年初推出了Java 8,并且已经在ThreeTen-Backport项目中向后移植到Java 6和7。 对于Android,请参阅ThreeTenABP项目。 所以现在老实说,我没有理由继续使用SimpleDateFormat
和Date
。 较新的类程序员更友好,更适合使用。
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);
结果(日期字符串): 01/20/1997