从 java.util.Date 中删除时间部分的正确方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7777543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the proper way to remove the time part from java.util.Date?
提问by Clark Bao
I want to implement a thread-safe function to remove the time part from java.util.Date.
我想实现一个线程安全函数来从 java.util.Date 中删除时间部分。
I tried this way
我试过这种方式
private static final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
public static Date removeTimeFromDate(Date date) {
Date returnDate = date;
if (date == null) {
return returnDate;
}
//just have the date remove the time
String targetDateStr = df.format(date);
try {
returnDate = df.parse(targetDateStr);
} catch (ParseException e) {
}
return returnDate;
}
and use synchronized or threadLocal to make it thread-safe. But it there any better way to implement it in Java. It seems this way is a bit verbose. I am not satisfied with it.
并使用 synchronized 或 threadLocal 使其成为线程安全的。但是它有更好的方法在 Java 中实现它。这种方式似乎有点冗长。我对此并不满意。
回答by Martijn Courteaux
A Date
object holds a variable wich represents the time as the number of milliseconds since epoch. So, you can't "remove" the time part. What you can do is set the time of that day to zero, which means it will be 00:00:00 000 of that day. This is done by using a GregorianCalendar:
一个Date
对象持有一个变量,它表示时间为自epoch以来的毫秒数。所以,你不能“删除”时间部分。您可以做的是将当天的时间设置为零,这意味着它将是当天的 00:00:00 000。这是通过使用 GregorianCalendar 完成的:
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.HOUR_OF_DAY, 0);
gc.set(Calendar.MINUTE, 0);
gc.set(Calendar.SECOND, 0);
gc.set(Calendar.MILLISECOND, 0);
Date returnDate = gc.getTime();
回答by Jon Skeet
A Date
holds an instantin time - that means it doesn't unambiguously specify a particular date. So you need to specify a time zone as well, in order to work out what date something falls on. You then need to work out how you want to represent the result - as a Date
with a value of "midnight on that date in UTC" for example?
ADate
持有一个瞬间- 这意味着它不会明确指定特定日期。所以,你需要指定一个时区,以及,为了工作什么东西日期适逢。然后,您需要确定如何表示结果 - 例如Date
,值为“该日期的午夜 UTC”?
You should also note that midnight itself doesn't occur on all days in all time zones, due to DST transitions which can occur at midnight. (Brazil is a common example of this.)
您还应该注意,由于 DST 转换可能发生在午夜,因此午夜本身不会出现在所有时区的所有日子。(巴西就是一个常见的例子。)
Unless you're reallywedded to Date
and Calendar
, I'd recommend that you start using Joda Timeinstead, as that allows you to have a value of type LocalDate
which gets rid of most of these problems.
除非你真的执着于Date
和Calendar
,我建议你开始使用约达时间代替,因为这可以让你有类型的值,LocalDate
它摆脱了大部分的这些问题。