android 如何在游标适配器的绑定视图中进行日期解析和格式化

How to do Date parsing and formating inside a bindview of cursor adapter in android

我已将我的日期保存在我的 sqlite table 中,例如 2016-04-20,我希望我的列表视图将它们显示为 20/4 /2016 并且我在游标适配器的绑定视图中使用以下内容

String InitialDate=cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2)));

SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
Date dateObj = curFormater.parse(InitialDate);
SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy");
String newDateStr = postFormater.format(dateObj);
textViewDate.setText(newDateStr);

但在我执行任何操作之前,解析部分显示未处理的异常 java.text.ParseException 我导入了

import java.text.SimpleDateFormat;
import java.util.Date;

你应该为 parse 方法调用使用 try/catch 块,因为它可以产生 checked exception:

Date dateObj = null;
try {
    dateObj = curFormater.parse(InitialDate);
} catch (ParseException e) {
    e.printStackTrace();
}

或者你可以从你的方法中重新抛出这个异常(你应该在方法签名中使用 throws ParseException 子句)

通过documentation

Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.

这是因为您正在调用的方法 可以 抛出异常而您没有处理它。看:

Date java.text.DateFormat.parse(String source) throws ParseException

Throws: ParseException - if the beginning of the specified string cannot be parsed.

这基本上意味着,如果您尝试将无意义的内容转换为日期,java.text.DateFormat class 将尽力而为,但如果不可能,则会抛出异常,您必须要么使用正确的 try-catch 语句捕获,要么只是重新抛出异常以便其他人可以处理它..

所以最后你的选择是:

  1. 重新抛出异常

t

public static void main(String[] args) throws ParseException {
    String InitialDate = new String("2016-04-20");
    SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
    Date dateObj = curFormater.parse(InitialDate);
    SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy");
    String newDateStr = postFormater.format(dateObj);
}
  1. 正确使用 try catch

使用....

public static void main(String[] args) {
    String InitialDate = new String("2016-04-20");
    SimpleDateFormat curFormater = new SimpleDateFormat("yyyy-MM-dd");
    Date dateObj;
    try {
        dateObj = curFormater.parse(InitialDate);
        SimpleDateFormat postFormater = new SimpleDateFormat("dd/MM/yyyy");
        String newDateStr = postFormater.format(dateObj);
    } catch (ParseException e) {
        e.printStackTrace();
        System.err.println("a non sense was here");
    }
}