问题描述
|
我已经尝试了很多次,但是我无法获得RSS应用程序以将pubDate正确格式化为更加用户友好的格式。
String str = \"26/08/1994\";
SimpleDateFormat formatter = new SimpleDateFormat(\"dd/MM/yyyy\"); //please notice the capital M
Date date = formatter.parse(str);
该代码看起来很简单,但是我在formatter.parse(str)上收到未处理的类型解析异常错误。一旦开始工作,我就需要将RSS发布日期转换为MM / dd。
设置文本的代码行在这里:
listPubdate.setText(myRssFeed.getList().get(position).getPubdate());
我只是将其更改为:
listPubdate.setText(date);
这看起来是如此简单,以至于让我发疯,以至于我找不到答案。
解决方法
在我看来,您实际上正在运行此程序并收到错误。正如其他人指出的那样,问题在于您需要将
formatter.parse
调用包装在try / catch块中。这是一个编译问题,而不是运行时问题。
解决此编译问题后,您拥有的代码将按预期工作。
使用第二个格式化程序获取所需的MM / dd输出。
String str = \"26/08/1994\";
SimpleDateFormat inputFormatter = new SimpleDateFormat(\"dd/MM/yyyy\"); //please notice the capital M
SimpleDateFormat outputFormatter = new SimpleDateFormat(\"MM/dd\");
try {
Date date = inputFormatter.parse(str);
String text = outputFormatter.format(date);
listPubdate.setText(text);
} catch (ParseException e ) {
e.printStackTrace();
}
, 你可以这样得到日期
// get the current date
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
并想以简单格式输入
String date=String.format(mDay+\"/\"+mMonth+\"/\"+mYear);
因此您可以非常轻松地使用它。
,
我在formatter.parse(str)上收到未处理的类型解析异常错误
为此,您需要通过声明当前正在执行的方法只是抛出该异常或捕获该异常来显式处理该异常。有关更多信息,我强烈建议您阅读Java教程中的“异常”课。
这是捕获异常的示例。
String str = \"26/08/1994\";
SimpleDateFormat formatter = new SimpleDateFormat(\"dd/MM/yyyy\"); //please notice the capital M
Date date;
try
{
date = formatter.parse(str);
}
catch (ParseException e)
{
// Handle error condition.
}
, SimpleDateformat.parse(String)引发一个已检查的异常……将其包装在try / catch块中。
, 下面是示例代码...请注意SimpleDateFormat构造函数中的格式。此日期要解析的字符串的格式应类似于在SimpleDateFormat构造函数中传递的字符串的格式
公共日期getDate(String str){
SimpleDateFormat sdFormat = new SimpleDateFormat(\“ EEE MMM dd hh:mm:ss \”);
日期d =空;
try {
String str1 = str.substring(0,str.lastIndexOf(\" \")).substring(0,str.lastIndexOf(\" \"));
String str2 = str1.substring(0,str1.lastIndexOf(\" \"));
Log.v(\"str1\",str2);
d = sdFormat.parse(str2);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}