开发者

What's the right way to create a date in Java? [duplicate]

开发者 https://www.devze.com 2023-03-14 09:55 出处:网络
This question already has answers here: Java Date vs Calendar (13 answers) Closed 8 years ago. I get confused by the Java API for the Date class. Everything seems to be deprecated and links
This question already has answers here: Java Date vs Calendar (13 answers) Closed 8 years ago.

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.

Is there a simple way to do that? For now I do

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, 开发者_如何学Pythonday, hour, minute, second);
Date date = cal.getTime(); // get back a Date object


You can use 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 right than to use Calendar ...


The excellent joda-time library is almost always a better choice than Java's Date or Calendar classes. Here's a few examples:

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);


You can try joda-time.

0

精彩评论

暂无评论...
验证码 换一张
取 消