【发布时间】:2018-11-18 05:05:36
【问题描述】:
我有以下代码。我正在传递start = "2016/01/01 23:59:59" 和end = "2017/01/01 23:59:59"
func(String start, String end) {
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date1 = sdf1.parse(start);
long startTime = date1.getTime();
\\System.out.println(startTime);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date2 = sdf2.parse(end);
long endTime = date2.getTime();
\\System.out.println(endTime);
}
我收到以下错误
error: unreported exception ParseException; must be caught or declared to be thrown
Date date = sdf.parse(time);
^
我该如何纠正这个问题?还有,为什么会显示这个错误?
【问题讨论】:
-
我建议你避开
SimpleDateFormat班级和朋友。它不仅过时了,而且出了名的麻烦。今天我们在java.time, the modern Java date and time API 中做得更好。LocalDateTime.parse(start, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss")).atZone(ZonId.systemDefault()).toInstant().toEpochMilli(). -
作为 Ole V.V.评论说,仅供参考,非常麻烦的旧日期时间类,例如
java.util.Date、java.util.Calendar和java.text.SimpleDateFormat现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代。见Tutorial by Oracle。 -
提示:
String::replace( " " , "T" )、LocalDateTime.parse、LocalDateTime::atZone、ZoneId、ZonedDateTime::toInstant()、Instant::toEpochMilli。 -
@OleV.V.我可以知道使用这些内置函数的时间复杂度吗?
-
我不知道,@yahooo。对我来说从来都不是问题。我通常希望他们花费恒定的时间。
标签: java string date string-parsing