我正在尝试转换 java.util.date 中的字符串,但出现以下错误:
HelloWorld.java:10: error: incompatible types: Date cannot be converted to String
return FORMATTER.parse(date);
^
HelloWorld.java:16: error: incompatible types: String cannot be converted to Date
Date date = convertStringToDate("2015-08-03 09:19:00.000");
我的代码如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class HelloWorld{
private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
public static String convertStringToDate(String date) {
if(date!=null){
return FORMATTER.parse(date);
}
return null;
}
public static void main(String []args){
Date date = convertStringToDate("2015-08-03 09:19:00.000");
System.out.println(date);
}
}
最佳答案
将您的方法签名更改为:
public static Date convertStringToDate(String date)
SimpleDateFormat.parse
返回一个 Date
,而不是 String
。
此外,您还需要处理 parse
方法可能抛出的已检查的 ParseException
,方法是在签名中声明 throws ParseException
(以及在 main
中处理异常),或者将异常包装到 RuntimeException
中(在给出错误输入时有效地终止程序):
public static Date convertStringToDate(String date) {
if (date != null) {
try {
return FORMATTER.parse(date);
} catch (ParseException e) {
// nothing we can do if the input is invalid
throw new RuntimeException(e);
}
}
return null;
}
最后,您应该注意到,您只能使用当前格式 (yyyy-MM-dd hh:mm:ss
) 解析 1 到 12 范围内的小时值。如果您想根据 24 小时制进行解析,则应使用 HH
模式来代替小时部分:
private static final DateFormat FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
关于java - 将字符串转换为 java.util.date,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32193539/