java.util.Date格式转换yyyy-mm-dd到mm-dd-yyyy [英] java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
问题描述
我有一个 java.util.Date
,格式为 yyyy-mm-dd
。我想要的格式是 mm-dd-yyyy
I have a java.util.Date
in the format yyyy-mm-dd
. I want it to be in the format mm-dd-yyyy
以下是我试过的这个转换:
Below is the sample util I tried out for this conversion:
// 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
。
Still the output I am getting is not in the format mm-dd-yyyy
.
请告诉我如何格式化 java.util.Date
从 yyyy-mm-dd
到 mm-dd-yyyy
Kindly let me know how to format a java.util.Date
from yyyy-mm-dd
to mm-dd-yyyy
推荐答案
日期
是自Unix纪元以来的毫秒数的容器(1970年1月1日00:00:00 UTC) )
Date
is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
它没有格式的概念。
例如...
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
None of the formatting has changed the underlying Date
value. This is the purpose of the DateFormatter
s
更新了其他示例
为了防止第一个例子没有意义...
Just in case the first example didn't make sense...
此示例使用两个格式化器格式化日期。然后我使用这些相同的格式化程序将 String
值解析为 Date
s。所得到的解析不会改变 Date
报告它的价值。
This example uses two formatters to format the same date. I then use these same formatters to parse the String
values back to Date
s. The resulting parse does not alter the way Date
reports it's value.
Date#toString
只是转载它的内容。你不能改变这个,但你可以格式化 Date
对象任何你喜欢的方式
Date#toString
is just a dump of it's contents. You can't change this, but you can format the Date
object any way you like
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
,以确保您没有使用错误的模式;)
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat
to make sure you're not using the wrong patterns ;)
这篇关于java.util.Date格式转换yyyy-mm-dd到mm-dd-yyyy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!