2011-11-23 60 views
0

我是新的啓動器android。 我有一個簡單的問題。當我通過datePickerDialog選擇日期並按下確認按鈕時,我想將日期存儲爲日期格式而不是字符串。 如何存儲日期格式?Android數據庫日期類型

private static final String DATABASE_CREATE = 
"create table fridge_table (_id integer primary key autoincrement, "+ 
"category text not null, name texct not null, expired_date text not null);"; 

public void onCreate(SQLiteDatabase db) 
{ 
    db.execSQL(DATABASE_CREATE); 
} 

如何更改expired_Date字段?有些人說使用長或日期。 我想知道如何在sqlite中存儲。

我想要轉換日期,我想通過此字段設置警報。 你能幫我嗎?如果你有任何例子,請給我一些例子。

回答

2

然後您可以使用日曆對象。

您可以節省時間,如:

Calendar cal=Calendar.getInstance(); 
//set date,month,year,time etc. according to your need to cal object 
//add expired_date's value as cal.getTimeInMillis() 

您也可以使用檢索相同:

long date=cursor.getLong(cursor.getColumnIndex("expired_date")); 
Calendar cal=Calendar.getInstance(); 
cal.clear(); 
cal.setTimeInMillis(date); 
// you can use any format to display this time using String.format() method. 

對於各種日期格式選項,請訪問:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

編輯:

對於前充足:

Calendar cal=Calendar.getInstance(); 
String date_time=String.format("%1$te %1$tB %1$tY,%1$tI:%1$tM:%1$tS %1$Tp",cal); 
Toast.makeText(getApplicationContext(),date_time,Toast.LENGTH_SHORT).show(); 
//this will show a toast containing current date and time in format "23 January 2010,12:30:15 pm" 
+0

這意味着我必須首先將字符串類型更改爲Long類型? – wholee1

+0

其實不是......你只需要改變時間/日期。你可以在我的答案中使用所提供的鏈接中的同伴將它轉換爲人類可讀的字符串。請看我編輯的答案。我在那裏給你一個例子! – Hiral

+0

謝謝你的回覆。我正在嘗試處理您的編碼,但仍然無效。我正在嘗試String date_format = String.format(「%td-%tm-%tY」,cal);而不是時間。這樣對嗎?原文像'24/11/2011'。它是正確的格式,我是否必須將' - '更改爲'/'?當我嘗試這個,我不明白它.. – wholee1

3

SQLite版本3僅支​​持以下數據類型,因此您不能將日期存儲爲日期類型。 檢索和數據庫

NULL. The value is a NULL value. 
INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes 
    depending on the magnitude of the value. 
REAL. The value is a floating point value, stored as an 8-byte IEEE floating 
    point number. 
TEXT. The value is a text string, stored using the database encoding (UTF-8, 
    UTF-16BE or UTF-16LE). 
BLOB. The value is a blob of data, stored exactly as it was input. 
0

您可以將日期從它的格式轉換爲長型存儲時,您應該使用Calendar類的Java做的文本日期轉換,所以你必須在長期數據毫秒類型。然後,您可以將Long中的毫秒數轉換爲字符串並將其存儲爲TEXT數據類型的數據庫。

相關問題