How do I get a Date without time in Java?
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 by method 1
, meanwhile method 2
seems like a hack instead of a solution.
Do you absolutely have to use java.util.Date
? I would thoroughly recommend that you use Joda Time or the java.time
package from Java 8 instead. In particular, while Date and Calendar always represent a particular instant in time, with no such concept as "just a date", Joda Time does have a type representing this ( LocalDate
). Your code will be much clearer if you're able to use types which represent what you're actually trying to do.
There are many, many other reasons to use Joda Time or java.time
instead of the built-in java.util
types - they're generally far better APIs. You can always convert to/from a java.util.Date
at the boundaries of your own code if you need to, eg for database interaction.
以下是我用今天的日期设定为00:00:00
时间:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date today = new Date();
Date todayWithZeroTime = formatter.parse(formatter.format(today));
You can use the DateUtils.truncate from Apache Commons library.
Example:
DateUtils.truncate(new Date(), java.util.Calendar.DAY_OF_MONTH)
链接地址: http://www.djcxy.com/p/3042.html
上一篇: 在java中将字符串转换为Date
下一篇: 如何在没有Java的情况下获取日期?