在 Android SQLite 中处理日期的最佳方式 [英] Best way to work with dates in Android SQLite

查看:36
本文介绍了在 Android SQLite 中处理日期的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 SQLite 的 Android 应用程序上处理日期时遇到了一些问题.我有几个问题:

I'm having some trouble working with dates on my Android application that uses SQLite. I have a couple questions:

  1. 我应该使用什么类型在 SQLite 中存储日期(文本、整数、...)?
  2. 既然是存储日期的最佳方式,我该如何使用 ContentValues 正确存储它?
  3. 从 SQLite 数据库中检索日期的最佳方法是什么?
  4. 如何在 SQLite 上进行 sql 选择,按日期对结果进行排序?

推荐答案

您可以使用文本字段在 SQLite 中存储日期.

You can use a text field to store dates within SQLite.

以UTC格式存储日期,如果您使用datetime('now'),则默认情况下(yyyy-MM-dd HH:mm:ss) 将允许排序按日期列.

Storing dates in UTC format, the default if you use datetime('now') (yyyy-MM-dd HH:mm:ss) will then allow sorting by the date column.

SQLite 中以字符串形式检索日期,然后您可以使用日历或 android.text.format.DateUtils.formatDateTime 根据需要将它们格式化/转换为本地区域化格式方法.

Retrieving dates as strings from SQLite you can then format/convert them as required into local regionalised formats using the Calendar or the android.text.format.DateUtils.formatDateTime method.

这是我使用的区域化格式化方法;

Here's a regionalised formatter method I use;

public static String formatDateTime(Context context, String timeToFormat) {

    String finalDateTime = "";          

    SimpleDateFormat iso8601Format = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

    Date date = null;
    if (timeToFormat != null) {
        try {
            date = iso8601Format.parse(timeToFormat);
        } catch (ParseException e) {
            date = null;
        }

        if (date != null) {
            long when = date.getTime();
            int flags = 0;
            flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
            flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
            flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
            flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;

            finalDateTime = android.text.format.DateUtils.formatDateTime(context,
            when + TimeZone.getDefault().getOffset(when), flags);               
        }
    }
    return finalDateTime;
}

这篇关于在 Android SQLite 中处理日期的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆