問題:
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?