2012-10-28 150 views
5

我如何插入日期時間數據在我的sqlite數據庫使用contentvalues不使用原始查詢?在sqlite數據庫中插入datetime android

datetime('now')插入本身(文本)不是時間,我可以在當前時間添加額外的小時嗎?

一樣,當我按下按鈕「1小時」,將插入CURRENTTIME + 1小時sqlite的database..thanks,有點迷茫..

回答

6

轉換日期/時間以毫秒爲單位,你會得到一個long。然後,您只需在數據庫中插入long值。

如果日期/時間值以毫秒爲單位,則可以將日期/時間值一起添加。

--EDITED--

Date myDate = new Date(); 
    long timeMilliseconds = myDate.getTime(); 
    //add 1 hour 
    timeMilliseconds = timeMilliseconds + 3600 * 1000; //3600 seconds * 1000 milliseconds 
    //To convert back to Date 
    Date myDateNew = new Date(timeMilliseconds); 

在SQLite的java的long值被存儲爲int

+0

你能告訴我的語法,即時通訊真的無能爲力..我怎麼能轉換它? – mcr619619

+1

在我的回答中加入 – Luis

+0

謝謝!!!這就是我所需要的..當我插入它通過長,一切,我可以檢索和轉換它我想要的方式,但是當我通過格式化插入它(YYYY-DD -MM)我無法檢索它,如果我檢索它通過很長時間只回顧一年,如果通過getString,它只有一個字符串,我不能將其轉換爲實際毫,是否有工作?我可以使用長的方法,但它會更方便在我的數據庫中,如果它是一個可讀的一個..感謝..真正幫助我 – mcr619619

1

您不能使用使用Java包裝器「ContentValues」的日期時間函數。您可以在此方式實現:

1)您可以useSQLiteDatabase.execSQL(原始SQL查詢)

dbObj.execSQL("INSERT INTO "+DATABASE_TABLE+" VALUES (null, datetime()) "); 

2)可以使用的SimpleDateFormat

// setting the format to sql date time 
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Date date = new Date(); 
ContentValues initialValues = new ContentValues(); 
initialValues.put("date_time", dateFormat.format(date)); 
long recordId = mDb.insert(DB_TABLE_NAME, null, initialValues); 

3)你日期值存儲在數據庫顯示爲(長型)毫秒,並用於顯示您可以對其進行格式化,

import java.text.DateFormat; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 

System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS")); 

// Return date in specified format. 
// milliSeconds Date in milliseconds 
// dateFormat Date format 
// return date as string in specified format 

public static String formatDate(long milliSeconds, String dateFormat) 
{ 

    DateFormat formatter = new SimpleDateFormat(dateFormat); 

// Create a calendar object that will convert the date and time value in milliseconds to date. 
    Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(milliSeconds); 
return formatter.format(calendar.getTime()); 
    } 
} 

1 Second = 1000 M illiseconds,所以如果你想添加1小時,然後使用這個公式

currentTImeMilli + (60 * 60 * 1000) 
+0

我用第二個,但使用system.currentmills,然後格式化..謝謝。它的工作原理,現在我有一個新的問題,如果我檢索日期,「2012-10-28 09:58:15」我如何將它轉換爲system.currentmillis使用的格式?我需要的是因爲我的應用程序需要將當前時間與特定時間進行比較(在本例中爲+ 1小時) – mcr619619

相關問題