Rosdi Kasim Rosdi Kasim - 3 months ago 8
Java Question

How do I get a Date without time in Java?

Continuing from this discussion: java program to get the current date without timestamp

What is the most efficient way to get a Date object without the time? Is there any other way than these two?

//method 1
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));

//method 2
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
dateWithoutTime = cal.getTime();


Update:

1) I knew about Joda, I am just trying to avoid additional library for such a simple (I think) task. But based on the answers so far Joda seems extremely popular, so I might consider it.

2) By efficient, I mean I want to avoid temporary object
String
creation as used by
method 1
, meanwhile
method 2
seems like a hack instead of a solution.

Answer

Do you absolutely have to use java.util.Date? I would thoroughly recommend that you use Joda Time instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this (LocalDate). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.

There are many, many other reasons to use Joda Time instead of the built-in types - it's generally a far better API. You can always convert to/from a java.util.Date at the boundaries of your own code if you need to, e.g. for database interaction.

Comments