Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Sử dụng TIME() trong SQLite Android (UTC)

TIME() - Trích xuất giờ từ datetime

Hàm TIME() trả về phần thời gian (HH:MM:SS) từ chuỗi ngày giờ. Mặc định dùng UTC nếu không chỉ định modifier.

DatabaseHelper.java

public ArrayList<String> getAllContacts() {
    ArrayList<String> list = new ArrayList<>();
    SQLiteDatabase db = getReadableDatabase();
    
    // time(datetime, 'utc') lấy giờ UTC từ cột datetime
    Cursor cursor = db.rawQuery(
        "SELECT id, name, salary, TIME(datetime, 'utc') as utc_time " +
        "FROM " + TABLE_NAME, null);

    if (cursor.moveToFirst()) {
        do {
            int id = cursor.getInt(0);
            String name = cursor.getString(1);
            String salary = new String(cursor.getBlob(2));
            String utcTime = cursor.getString(3);
            list.add(id + " : " + name + " : " + salary + " : UTC " + utcTime);
        } while (cursor.moveToNext());
    }
    cursor.close();
    return list;
}

So sánh TIME() với các modifier

-- Giả sử datetime = '2024-01-15 14:30:45' (UTC)
SELECT 
    TIME(datetime)           AS default_utc,     -- 14:30:45
    TIME(datetime, 'utc')    AS explicit_utc,    -- 14:30:45
    TIME(datetime, 'localtime') AS local_time;   -- 21:30:45 (nếu UTC+7)

Kết quả

Sử dụng TIME() trong SQLite Android (UTC)

Hiển thị giờ UTC (14:30:45) thay vì giờ địa phương.

Ứng dụng thực tế

  • Lưu trữ UTC: Luôn lưu CURRENT_TIMESTAMP (UTC) để nhất quán cross-device.
  • Hiển thị local: Dùng 'localtime' khi SELECT để hiển thị cho user.
  • So sánh thời gian: So sánh trong UTC tránh lỗi DST/múi giờ.
  • API server: Gửi/receive ISO8601 UTC (yyyy-MM-dd'T'HH:mm:ss'Z').

Best Practice Android

// Java: Lấy thời gian hiện tại UTC
String utcNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(new Date());
// Hoặc
long utcMillis = System.currentTimeMillis();
String iso8601 = Instant.ofEpochMilli(utcMillis).toString(); // 2024-01-15T14:30:45Z

// Insert vào SQLite
ContentValues values = new ContentValues();
values.put("datetime", utcNow); // Hoặc iso8601
db.insert(TABLE_NAME, null, values);