2012-10-28 149 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

相关问题