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 you need the date part just for echoing purpose, then
Check out Veyder-time. It is a simple and efficient alternative to both java.util and Joda-time. It has an intuitive API and classes that represent dates alone, without timestamps.
The standard answer to these questions is to use Joda Time. The API is better and if you're using the formatters and parsers you can avoid the non-intuitive lack of thread safety of
SimpleDateFormat
.Using Joda means you can simply do:
Update:: Using java 8 this can be acheived using
Definitely not the most correct way, but if you just need a quick solution to get the date without the time and you do not wish to use a third party library this should do
I only needed the date for visual purposes and couldn't Joda so I substringed.