我需要处理一个字符串列表,这些列表可能是也可能不是。当我收到时间时,需要将“HH:mm:ss”转换为处理前的毫秒数:
final String unknownString = getPossibleTime();
final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
dateFormat.setLenient(false);
try {
final Date date = dateFormat.parse(unknownString);
//date.getTime() is NOT what I want here, since date is set to Jan 1 1970
final Calendar time = GregorianCalendar.getInstance();
time.setTime(date);
final Calendar calendar = GregorianCalendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
calendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
final long millis = calendar.getTimeInMillis();
processString(String.valueOf(millis));
}
catch (ParseException e) {
processString(unknownString);
}
此代码有效,但我真的不喜欢它。异常处理特别难看。如果不使用像Joda-Time这样的库,有没有更好的方法来实现这一目标?
答案 0 :(得分:2)
public static long getTimeInMilliseconds(String unknownString) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = dateFormat.format(Calendar.getInstance().getTime());
DateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return timeFormat.parse(dateString + " " + unknownString).getTime();
}
处理此方法之外的ParseException但是你喜欢。即("没有提供时间信息" ......或"未知时间格式" ......等)
.getTime()
以毫秒为单位返回时间。它是java.util.Date
API的一部分。
答案 1 :(得分:1)
为什么不先检查输入是否实际为HH:mm:ss格式。您可以首先尝试匹配输入到正则表达式[0-9]?[0-9]:[0-9]?[0-9]:[0-9]?[0-9]
,如果匹配则将其视为日期,否则调用processString(unknownString);