来自SQLite的Android格式日期

时间:2013-10-04 15:37:48

标签: android sqlite date view

我以支持的格式(yyyy-mm-dd)在sqlite数据库中插入日期。 现在我希望用户在查询时根据国家显示日期格式(意大利dd-mm-yyyy,美国yyyy-mm-dd等...)

我该怎么办?感谢

3 个答案:

答案 0 :(得分:5)

SQLite does not have a dedicated date and time数据类型。如果您插入类似“01-01-2013”​​的内容,它将像字符串一样存储,使得比较,排序和查询变得困难和缓慢,因为您需要使用SQLite日期函数对其进行转换。

您应该存储UNIX时间戳。这要求date列的类型为INTEGER。可以快速处理,排序和选择时间戳,例如,您可以使用Java的Calendar and DateFormat类以任何日期格式表示它们。您可以通过工厂方法检索appropriate format for the user's default locale

最重要的是Android的专用DateUtils类,它提供了各种功能,用于在用户的语言环境中创建日期时间和时间范围字符串。

答案 1 :(得分:2)

您还可以使用SQLite日期和时间格式化程序,例如:

SELECT strftime( '%d-%m-%Y', birthday) as birthday FROM people

答案 2 :(得分:1)

请尝试以下代码

String date = "2013-11-15"; // Retrived date in your specified format from sqlite
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date res = null;
    try {
        d = (Date)sdf.parse(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    Calendar c = Calendar.getInstance();
    c.setTime(d);

    String day = c.get(Calendar.DAY_OF_MONTH);
    String month = c.get(Calendar.MONTH);
    String year = c.get(Calendar.YEAR); 
//You can use these day, month and year string values to view in any format

希望这会对你有所帮助。谢谢。