How do I get a Date without time in Java?

2019-01-03 04:28发布

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:

  1. 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.

  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.

标签: java date
22条回答
干净又极端
2楼-- · 2019-01-03 05:32

If you need the date part just for echoing purpose, then

Date d = new Date(); 
String dateWithoutTime = d.toString().substring(0, 10);
查看更多
孤傲高冷的网名
3楼-- · 2019-01-03 05:32

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.

查看更多
Lonely孤独者°
4楼-- · 2019-01-03 05:33

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:

LocalDate d = new LocalDate();

Update:: Using java 8 this can be acheived using

LocalDate date = LocalDate.now();
查看更多
不美不萌又怎样
5楼-- · 2019-01-03 05:34

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

    Date db = db.substring(0, 10) + db.substring(23,28);

I only needed the date for visual purposes and couldn't Joda so I substringed.

查看更多
登录 后发表回答