如何在 Java 中创建具有特定格式的日期?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7777969/
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
How to create a Date with specific format in Java?
提问by Adham
I have the following code to handle date
我有以下代码来处理日期
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a");
String s = formatter.format(formatter.parse("10/11/2011 4:24:00 PM");
System.out.prinln(s);
Date d = (Date)formatter.parseObject(s);
System.out.println(d);
this first print line output is : 10/10/2011 00:00:00 AM
第一个打印行输出是: 10/10/2011 00:00:00 AM
and the second is : Mon Oct 10 00:00:00 GMT+02:00 2011
第二个是: Mon Oct 10 00:00:00 GMT+02:00 2011
How I can make the second statement print out the same as the first one?
如何使第二个语句打印出来与第一个语句相同?
edit
编辑
the question is how to create date object with this format ?
问题是如何用这种格式创建日期对象?
回答by Bozho
You can't. The toString()
method of objects is used mainly for debugging, and not for presenting to users.
你不能。toString()
对象的方法主要用于调试,不用于呈现给用户。
Always use a formatter. In your case: String formatted = formatter.format(d)
始终使用格式化程序。在你的情况下:String formatted = formatter.format(d)
The Date
object does not have a representation format. It only has the data. The formatter has the format.
该Date
对象不具有代表性的格式。它只有数据。格式化程序有格式。