如何在Java中沒有時間獲取日期? - How do I get a Date without time in Java?

問題:

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 : 更新

  1. 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似乎非常受歡迎,所以我可能會考慮它。

  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. 通過有效 ,我的意思是我想避免method 1使用的臨時對象String創建,同時method 2似乎是一個黑客而不是解決方案。


解決方案:

參考一: https://stackoom.com/question/LBmM
參考二: How do I get a Date without time in Java?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章