java Java日期格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/412435/
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
Java date formatting?
提问by user48094
I want to read a date in the format YYYY-MM-DD.
我想读取格式为 YYYY-MM-DD 的日期。
But if I enter date say for example 2008-1-1, I want to read it as 2008-01-01.
但是,如果我输入日期,例如 2008-1-1,我想将其读为 2008-01-01。
Can anybody help me? Thanks in advance
有谁能够帮我?提前致谢
回答by Ludwig Wensauer
Or use the much better Joda Timelib.
或者使用更好的Joda Timelib。
DateTime dt = new DateTime();
System.out.println(dt.toString("yyyy-MM-dd"));
// The ISO standard format for date is 'yyyy-MM-dd'
DateTimeFormatter formatter = ISODateTimeFormat.date();
System.out.println(dt.toString(formatter));
System.out.println(formatter.print(dt));
The Date and Calendar API is awful.
日期和日历 API 很糟糕。
回答by Adeel Ansari
回答by Jon Skeet
Adeel's solution is fine if you need to use the built-in Java date/time handling, but personally I'd much rather use Joda Time. When it comes to formats, the principle benefit of Joda Time is that the formatter is stateless, so you can share it between threads safely. Sample code:
如果您需要使用内置的 Java 日期/时间处理,Adeel 的解决方案很好,但我个人更愿意使用Joda Time。在格式方面,Joda Time 的主要好处是格式化程序是无状态的,因此您可以在线程之间安全地共享它。示例代码:
DateTimeFormatter parser = DateTimeFormat.forPattern("YYYY-M-D");
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-DD");
DateTime dt = parser.parseDateTime("2008-1-1");
String formatted = formatter.print(dt); // "2008-01-01"
回答by Fernando Miguélez
import java.text.*;
public class Test
{
public static void main(String args[])
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-DD");
System.out.println(sdf.parse(args[0]).toString());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
This works OK, no matter if you write as argument "2008-1-1" or "2008-01-01".
这工作正常,无论你是写成参数“2008-1-1”还是“2008-01-01”。

