【发布时间】:2011-12-08 07:37:57
【问题描述】:
我想实现一个线程安全的函数来从 java.util.Date 中删除时间部分。
我试过这种方式
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;
}
并使用 synchronized 或 threadLocal 使其成为线程安全的。 但它有更好的方法来用 Java 实现它。这种方式似乎有点冗长。 我对此并不满意。
【问题讨论】:
-
顺便说一句,但为 thread-safety reasons 保留对 DateFormat 的静态引用通常是不明智的。
-
你是对的。在知道它需要是线程安全的之后,我改变了它。