繁体   English   中英

如何在Android中的游标适配器的bindview中进行日期解析和格式化

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

我已经将日期保存在像2016-04-20这样的sqlite表中,并且希望列表视图将日期显示为20/4/2016,并且在游标适配器的bindview中使用以下内容

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;

这是因为您正在调用的方法可能会引发异常,并且您没有在意它。

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

抛出:ParseException-如果无法分析指定字符串的开头。

这基本上意味着,如果您尝试将无意义的日期转换为日期,则java.text.DateFormat类将尽力而为,但如果不可能,将引发异常,您必须使用正确的try-catch语句进行捕获或者只是抛出异常,以便其他人可以处理它。

因此,最后您可以选择:

  1. 重新抛出异常

Ť

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. 使用正确的尝试抓住

采用....

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");
    }
}

您应该使用try / catch块进行parse方法调用,因为它可能产生已检查的异常

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

或者您可以从方法中抛出该异常(您应该在方法签名中使用throws ParseException子句)

通过文档

已检查的异常受“捕获”或“指定要求”的约束。 除Error,RuntimeException及其子类指示的那些异常外,所有异常都是经过检查的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM