在 Java 中创建日期的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6437257/
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
What's the right way to create a date in Java?
提问by seb
I get confused by the Java API for the Date class. Everything seems to be deprecated and links to the Calendar class. So I started using the Calendar objects to do what I would have liked to do with a Date, but intuitively it kind of bothers me to use a Calendar object when all I really want to do is create and compare two dates.
我对 Date 类的 Java API 感到困惑。一切似乎都已弃用,并链接到 Calendar 类。所以我开始使用 Calendar 对象来做我想要用 Date 做的事情,但从直觉上讲,当我真正想做的只是创建和比较两个日期时,使用 Calendar 对象有点困扰我。
Is there a simple way to do that? For now I do
有没有一种简单的方法可以做到这一点?现在我做
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, hour, minute, second);
Date date = cal.getTime(); // get back a Date object
回答by Chris Knight
The excellent joda-timelibrary is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:
优秀的joda-time库几乎总是比 Java 的 Date 或 Calendar 类更好的选择。下面是几个例子:
DateTime aDate = new DateTime(year, month, day, hour, minute, second);
DateTime anotherDate = new DateTime(anotherYear, anotherMonth, anotherDay, ...);
if (aDate.isAfter(anotherDate)) {...}
DateTime yearFromADate = aDate.plusYears(1);
回答by Maxx
You can use SimpleDateFormat
您可以使用SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date d = sdf.parse("21/12/2012");
But I don't know whether it should be considered more rightthan to use Calendar ...
但我不知道是否应该认为它比使用 Calendar更正确......