问题:
Continuing from Stack Overflow question Java program to get the current date without timestamp : 继续Stack Overflow问题Java程序以获取没有时间戳的当前日期 :
What is the most efficient way to get a Date object without the time? 没有时间获取Date对象的最有效方法是什么? 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 ; 我知道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. 但基于迄今为止的答案,Joda-Time似乎非常受欢迎,所以我可能会考虑它。
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. 通过有效 ,我的意思是我想避免method 1
使用的临时对象String
创建,同时method 2
似乎是一个黑客而不是解决方案。
解决方案:
参考一: https://stackoom.com/question/LBmM参考二: How do I get a Date without time in Java?