【发布时间】:2015-08-28 04:26:06
【问题描述】:
如何使用 contentvalues 而不使用原始查询在我的 sqlite 数据库中插入日期时间数据?
datetime('now') 插入自身(文本)而不是时间,我可以在当前时间中添加额外的小时数吗?
就像,当我按下按钮“1HOUR”时,它会在 sqlite 数据库中插入当前时间 + 1 小时..谢谢,有点困惑..
【问题讨论】:
如何使用 contentvalues 而不使用原始查询在我的 sqlite 数据库中插入日期时间数据?
datetime('now') 插入自身(文本)而不是时间,我可以在当前时间中添加额外的小时数吗?
就像,当我按下按钮“1HOUR”时,它会在 sqlite 数据库中插入当前时间 + 1 小时..谢谢,有点困惑..
【问题讨论】:
将日期/时间转换为毫秒,你会得到一个long。然后你只需在数据库中插入long 值。
如果日期/时间值以毫秒为单位,您可以将它们相加。
--已编辑--
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。
【讨论】:
您不能通过 Java 包装器“ContentValues”使用日期时间函数。您可以通过这种方式实现:
1) 可以使用SQLiteDatabase.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 秒 = 1000 毫秒,所以如果你想增加 1 小时,请使用这个公式
currentTImeMilli + (60 * 60 * 1000)
【讨论】: