如何在 Java 中获得没有时间的日期? [英] How do I get a Date without time in Java?
问题描述
继续堆栈溢出问题Java 程序获取没有时间戳的当前日期:
Continuing from Stack Overflow question Java program to get the current date without timestamp:
在没有时间的情况下获取 Date 对象的最有效方法是什么?除了这两个还有别的办法吗?
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();
更新:
我知道 Joda-Time;我只是想避免为这样一个简单(我认为)的任务添加额外的库.但根据目前的答案,Joda-Time 似乎非常受欢迎,所以我可能会考虑.
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.
通过高效,我的意思是我想避免方法1
使用的临时对象String
创建,同时方法 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.util.Date
吗?我彻底建议您使用Joda Time 或java.java 8 中的 time
包.特别是,虽然 Date 和 Calendar 总是表示一个特定的时刻,没有只是一个日期"这样的概念,但 Joda Time 确实有一个类型来表示这个(<代码>本地日期代码>).如果您能够使用代表您实际尝试执行的操作的类型,您的代码将会更加清晰.
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.
使用 Joda Time 或 java.time
而不是内置的 java.util
类型的原因有很多很多 - 它们通常是更好的 API.如果需要,您始终可以在自己的代码边界处与 java.util.Date
进行转换,例如用于数据库交互.
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, e.g. for database interaction.
这篇关于如何在 Java 中获得没有时间的日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!