Continuing from Stack Overflow question 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:
I knew about Joda-Time; I am just trying to avoid additional library for such a simple (I think) task. But based on the answers so far Joda-Time seems extremely popular, so I might consider it.
By efficient, I mean I want to avoid temporary object
String
creation as used bymethod 1
, meanwhilemethod 2
seems like a hack instead of a solution.
If all you want is to see the date like so "YYYY-MM-DD" without all the other clutter e.g. "Thu May 21 12:08:18 EDT 2015" then just use
java.sql.Date
. This example gets the current date:Also
java.sql.Date
is a subclass ofjava.util.Date
.Do you absolutely have to use
java.util.Date
? I would thoroughly recommend that you use Joda Time or thejava.time
package from Java 8 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 or
java.time
instead of the built-injava.util
types - they're generally far better APIs. You can always convert to/from ajava.util.Date
at the boundaries of your own code if you need to, e.g. for database interaction.The most straightforward way:
I just made this for my app :
Android API level 1, no external library. It respects daylight and default timeZone. No String manipulation so I think this way is more CPU efficient than yours but I haven't made any tests.
This is a simple way of doing it:
Here is a clean solution with no conversion to string and back, and also it doesn't re-calculate time several times as you reset each component of the time to zero. It also uses
%
(modulus) rather than divide followed by multiply to avoid the double operation.It requires no third-party dependencies, and it RESPECTS THE TIMEZONE OF THE Calender object passed in. This function returns the moment in time at 12 AM in the timezone of the date (Calendar) you pass in.