可能的原因是
SimpleDateFormat不是线程安全的事实,并且您正在从多个线程中引用它。虽然 极其
困难的证明(约一样难以测试),有一些证据是这种情况:
.11331133EE22
-注意一切都翻了一番880044E.3880044E3
- 同样在这里
您可能至少有两个线程交织。这
E让我感到困惑,我认为它正在尝试处理科学计数法(例如1E10等),但这可能是 时区的 一部分。
幸运的是,(格式化)基本修复很简单:
private static final String FORMAT_STRING = "HH:mm:ss.SSSZ";public static Date getCurrentTimeonly() { SimpleDateFormat formatter = new SimpleDateFormat(FORMAT_STRING); String onlyTimeStr = formatter.format(new Date()); return formatter.parse(onlyTimeStr);}您还可以在这里做其他几件事,但要注意以下几点:
1-如果时区为UTC(或任何不带DST的时区),这是微不足道的
public static Date getCurrentTimeonly() { Date time = new Date(); time.setTime(time.getTime() % (24 * 60 * 60 * 1000)); return time;}2-您将无法测试此方法,因为您不能安全地暂停时钟(可以更改时区/区域设置)。为了更好地处理Java中的日期/时间,请使用JodaTime之类的东西。请注意,
LocalTime它没有附加时区,而
Date仅返回
整数小时
的偏移量(并且存在不在hour上的时区);为了安全起见,您需要返回一个
Calendar(带有完整时区),或者只返回没有它的东西:
// This method is now more testable. Note this is only safe for non-DST zonespublic static Calendar getCurrentTimeonly() { Calendar cal = new Calendar(); // DateTimeUtils is part of JodaTime, and is a class allowing you to pause time! cal.setTimeInMillis(DateTimeUtils.currentTimeMillis() % (24 * 60 * 60 * 1000)); return cal;}


