JAVA + SQLite - 使用 strftime() 从每一行获取格式化日期

JAVA + SQLite - get a formatted date from each row using strftime()

我现在已经使用 SQLite 大约一天了,并且已经成功地使用 Java 在 Android Studio 中进行读写工作。我对这一切还很陌生,甚至 java,所以我可能遗漏了一些非常基本的东西。

昨天我设法让一些东西工作并取得了预期的结果。我会将年、月、...、秒保存到它们自己的列中,然后单独读取它们并手动将它们格式化为字符串。但是今天我读到,当您将 SQLite 以特定格式存储为文本时,它有自己的内置日期和时间函数。

我已更改所有内容以改用此格式,这很简单,但我很难以特定格式读取日期。现在的格式是:

yyyy-MM-dd HH:mm:ss

不过,我想将其格式化为:

yyyy : MM : dd : HH : mm : ss

我现在只是将它存储在一个字符串列表中,这有效,我认为我不需要更改它。

这是读取日期的代码:

public ArrayList readHistory(){
        SQLiteDatabase nutDatabase = this.getReadableDatabase();
        ArrayList<String> history = new ArrayList<String>();

        Cursor cursor = nutDatabase.rawQuery("select * from " + TABLE_NAME, null);
        cursor.moveToFirst();

        while (!cursor.isAfterLast()){
            String nutString = cursor.getString(dateTime);
            history.add(nutString);
            cursor.moveToNext();
        }
        return history;
    }

如您所见,它目前只是将其作为当前格式的字符串获取。我不知道如何实现 strftime(),但我知道它正是我需要的。

欢迎任何意见,谢谢!

strftime()中使用格式'%Y : %m : %d : %H : %M : %S'
因此,将您的代码更改为:

String sql = "SELECT strftime('%Y : %m : %d : %H : %M : %S', dateTime) AS dateTime FROM " + TABLE_NAME;
Cursor cursor = nutDatabase.rawQuery(sql, null);

java.time

使用 SQL 解决它的替代方法,您可以使用 java.time API 解决它,如下所示:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss", Locale.ENGLISH);
        // A sample date-time string. In your code, it will come from
        // cursor.getString(dateTime)
        String nutString = "2020-01-10 20:30:40";
        LocalDateTime ldt = LocalDateTime.parse(nutString, dtfInput);

        DateTimeFormatter dtfOutput = DateTimeFormatter.ofPattern("uuuu : MM : dd HH : mm : ss", Locale.ENGLISH);
        String formatted = dtfOutput.format(ldt);
        System.out.println(formatted);
        // history.add(formatted);
    }
}

输出:

2020 : 01 : 10 20 : 30 : 40

正如您在代码中看到的那样,您需要 DateTimeFormatter 的两个实例 - 一个用于解析日期时间字符串,您正在从数据库中检索到 LocalDateTime,另一个用于格式化LocalDateTime 到所需格式的 String

Trail: Date Time.

了解现代日期时间 API