无法将我的字符串转换为日期 [英] Cannot convert my String to Date
问题描述
我正在搜索如何将字符串转换为日期,因此我在stacko上找到了一些示例。 。所以我用了SimpleDateFormat并尝试解析,但是我的编译器(AndroidStudio的Gradle)向我发送此错误:未处理的异常:java.text.ParseException。
这是我的代码:
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 :
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
[...]
}
为什么会出现错误?有人可以向我解释吗?
我是Java的初学者,对我的英语不好对不起,我希望有人能对此提供帮助。
谢谢
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
推荐答案
parse
方法抛出 ParseException
。您需要插入 catch
块,否则您的方法应该抛出 ParseException
来消除错误:
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:
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);
}
这篇关于无法将我的字符串转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!