java 无法将我的字符串转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17399761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cannot convert my String to Date
提问by bengous
i was searching how to convert a string to a date, so i've found some examples on stacko. . So i used SimpleDateFormat and tried to parse but my compiler (Gradle from AndroidStudio) send me this error : Unhandled exception : java.text.ParseException. There is my code :
我正在搜索如何将字符串转换为日期,所以我在 stacko 上找到了一些示例。. 所以我使用 SimpleDateFormat 并尝试解析,但我的编译器(来自 AndroidStudio 的 Gradle)向我发送了这个错误:未处理的异常:java.text.ParseException。有我的代码:
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1); // there is the error
[...]
}
Why is there an error? Someone can explain that to me? I'm a beginner in java and i'm sorry for my bad english, and i hope someone can help me on this. Thanks
为什么会出现错误?有人可以向我解释一下吗?我是 Java 的初学者,很抱歉我的英语不好,我希望有人能帮助我。谢谢
回答by Rahul Bobhate
The parse
method throws a ParseException
. You need to insert a catch
block or your method should throw ParseException
in order to get rid of the error:
该parse
方法抛出一个ParseException
. 您需要插入一个catch
块或您的方法应该抛出ParseException
以消除错误:
public static int compareDate(String sdate1, String sdate2) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
try {
Date date1 = simpleDateFormat.parse(sdate1);
} catch (ParseException e) { // Insert this block.
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OR
或者
public static int compareDate(String sdate1, String sdate2) throws ParseException{
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd", Locale.FRANCE);
Date date1 = simpleDateFormat.parse(sdate1);
}