我有一个java.util.Date
格式yyyy-mm-dd
。我希望它采用以下格式mm-dd-yyyy
以下是我尝试进行此转换的示例util:
// Setting the pattern
SimpleDateFormat sm = new SimpleDateFormat("mm-dd-yyyy");
// myDate is the java.util.Date in yyyy-mm-dd format
// Converting it into String using formatter
String strDate = sm.format(myDate);
//Converting the String back to java.util.Date
Date dt = sm.parse(strDate);
我得到的输出仍然不是格式mm-dd-yyyy
。
请让我知道如何格式化java.util.Date
从yyyy-mm-dd
到mm-dd-yyyy
Date
是自Unix纪元(1970年1月1日UTC:00:00)以来的毫秒数的容器。
它没有格式的概念。
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
输出...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
您应该利用ThreeTen Backport
例如...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
输出...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
没有一种格式更改了基础Date
值。这是DateFormatter
s 的目的
更新了其他示例
万一第一个例子没有道理...
本示例使用两个格式化程序来格式化同一日期。然后,我使用这些相同的格式化程序将String
值解析回Date
s。产生的解析不会改变Date
报告其值的方式。
Date#toString
只是其中内容的转储。您不能更改此设置,但是可以Date
按照自己喜欢的任何方式格式化对象
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
哪个输出...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
另外,请注意格式模式。仔细检查SimpleDateFormat
以确保您没有使用错误的模式;)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句