Android:我无法弄清楚SimpleDateFormat

时间:2011-06-15 15:52:18

标签: java android date simpledateformat

我已经尝试过,但是我无法使用我的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 Pubdate转换为MM / dd。

为此设置文本的代码行是:

  listPubdate.setText(myRssFeed.getList().get(position).getPubdate());

我是否只需将其更改为:

  listPubdate.setText(date);

这看起来很简单,让我疯狂,我无法找到答案。

5 个答案:

答案 0 :(得分:3)

您可以通过此

获取日期
// 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);

所以你可以很容易地使用它。

答案 1 :(得分:1)

  

我在formatter.parse(str)上得到一个未处理的类型解析异常错误

为此,您需要显式处理异常,方法是声明当前正在执行的方法只是抛出它,或者通过捕获它。有关详细信息,我强烈建议您浏览the Exceptions Lesson in the Java Tutorial

以下是捕获异常的示例。

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.
}

答案 2 :(得分:1)

听起来像你实际上正在运行并得到错误。正如其他人指出的那样,问题是您需要将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();
    }

答案 3 :(得分:0)

SimpleDateformat.parse(String)抛出一个已检查的异常...将其包装在try / catch块中。

答案 4 :(得分:0)

下面是示例代码...注意SimpleDateFormat构造函数中的格式。要为日期解析的字符串的格式应与SimpleDateFormat构造函数中传递的字符串类似

public Date 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;
}
相关问题