本文介绍了SimpleDateFormat解析返回错误的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码:
public static String formatMinSecOrHourMinSec(final String length) {
try {
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss", Locale.GERMAN);
final Date date = hhmmss.parse(length);
final GregorianCalendar gc0 = new GregorianCalendar(Locale.GERMAN);
gc0.setTime(date);
if(gc0.getTimeInMillis() >= 3600 * 1000){
return hhmmss.format(gc0.getTime());
}else{
final SimpleDateFormat mmss = new SimpleDateFormat("mm:ss");
return mmss.format(gc0.getTime());
}
} catch (final ParseException e) {
LOGGER.debug("Konnte die Länge nicht parsen: " + length + "\n" + e);
return length;
}
}
如果length
设置为 01:29:00 ,我估计它将返回 01:29:00 ,但它返回 29:00 强>.这是因为gc0.getTimeInMillis()
返回的时间比预期少一小时(3600 * 1000).我在做什么错了?
I estimate that it returns 01:29:00 if length
is set to 01:29:00 but it returns 29:00. This is because gc0.getTimeInMillis()
returns one hour less (3600 * 1000) than expected. What am I doing wrong ?
推荐答案
这是因为java.util.Date使用的是您的默认时区. (从date
以毫秒为单位的打印时间,您将看到).要解决此问题,请尝试:
this is because java.util.Date is using your default time zone. (print time in ms from date
and you will see).To fix it try:
final SimpleDateFormat hhmmss = new SimpleDateFormat("HH:mm:ss");
hhmmss.setTimeZone(TimeZone.getTimeZone("UTC"));
这篇关于SimpleDateFormat解析返回错误的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!