如何使用SimpleDateFormat将String转换为Date? [英] How to convert a String to a Date using SimpleDateFormat?
本文介绍了如何使用SimpleDateFormat将String转换为Date?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码片段:
DateFormat formatter1;
formatter1 = new SimpleDateFormat("mm/DD/yyyy");
System.out.println((Date)formatter1.parse("08/16/2011"));
当我运行这个,我得到这个作为输出:
When I run this, I get this as the output:
Sun Jan 16 00:10:00 IST 2011
我预计:
Tue Aug 16 "Whatever Time" IST 2011
我的意思是说我没有按预期得到月。错误是什么?
I mean to say I am not getting the month as expected. What is the mistake?
推荐答案
尝试这样:
new SimpleDateFormat("MM/dd/yyyy")
-
MM
是月(不是mm
) -
dd
是day(不是DD
) MM
is "month" (notmm
)dd
is "day" (notDD
)-
mm
是分钟 -
DD
是一年中 mm
is "minutes"DD
is "day in year"
FYI,您的格式仍然是有效日期格式的原因是:
FYI, the reason your format is still a valid date format is that:
此外,您不需要转换为 Date
...它已经是 a Date
(或它爆炸):
Also, you don't need the cast to Date
... it already is a Date
(or it explodes):
public static void main(String[] args) throws ParseException {
System.out.println(new SimpleDateFormat("MM/dd/yyyy").parse("08/16/2011"));
}
输出:
Tue Aug 16 00:00:00 EST 2011
Voila !
这篇关于如何使用SimpleDateFormat将String转换为Date?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文