Android 从SQLite时间戳获取正确的日期和时间(时区、日光)
好吧,我会发疯的。我已经测试了许多解决方案,但没有得到正确的结果 让我解释一下:我已经用SQLite数据库创建了一个应用程序。在一张表上,我记录了一些关于用户当前位置的信息,比如纬度、经度和时间戳 我之所以选择时间戳,是因为它与格式无关。我将在稍后的显示中对其进行格式化 这是问题的开始 我创建了一个函数,将时间戳转换为日期和时间的字符串表示形式。容易的是的,这是我以前想的 这是包含一些垃圾测试的函数:Android 从SQLite时间戳获取正确的日期和时间(时区、日光),android,sqlite,date,timezone,timestamp,Android,Sqlite,Date,Timezone,Timestamp,好吧,我会发疯的。我已经测试了许多解决方案,但没有得到正确的结果 让我解释一下:我已经用SQLite数据库创建了一个应用程序。在一张表上,我记录了一些关于用户当前位置的信息,比如纬度、经度和时间戳 我之所以选择时间戳,是因为它与格式无关。我将在稍后的显示中对其进行格式化 这是问题的开始 我创建了一个函数,将时间戳转换为日期和时间的字符串表示形式。容易的是的,这是我以前想的 这是包含一些垃圾测试的函数: private String getDate(Timestamp timestamp) {
private String getDate(Timestamp timestamp) {
/*Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.getDefault());
cal.setTimeInMillis(timestamp.getTime());
String date = DateFormat.format("dd/MM/yyyy HH:mm", cal).toString();*/
//Time time = new Time(Time.getCurrentTimezone());
/*Time time = new Time();
time.set(timestamp.getTime());
time.switchTimezone(Time.getCurrentTimezone());
//String date = time.format3339(false);
String date = time.format2445();*/
//String date = DateFormat.getDateFormat(this).format(new Date(timestamp.getTime()));
//String date = DateUtils.formatDateTime(this, timestamp.getTime(), DateUtils.FORMAT_NUMERIC_DATE | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME);
String date = DateFormat.getDateFormat(this).format(new Date(timestamp.getTime())) + " " + DateFormat.getTimeFormat(this).format(new Date(timestamp.getTime()));
return date;
}
问题是显示的时间不正确!例如,时间戳是今天21:01,但它显示的内容类似于2014年4月9日19:01。差两个小时
在我测试的每个解决方案中,差异都是相同的。为什么两个小时?我想现在是UTC时间。但我注意时区
需要注意的是,我有生成时间戳的位置。也许他可以用来确定正确的时区
有什么建议或解决方案不是很容易的吗
附言:我住在瑞士
编辑:
创建条目时会自动创建时间戳“创建\u时间戳”时间戳默认当前\u时间戳不为空
下面是我用来读取数据库位置的两个函数:
public Location getLocation(long id) {
Cursor cursor = db.query(LocationSQLiteHelper.TABLE_NAME, allColumns, LocationSQLiteHelper.COLUMN_ID + " = " + id, null, null, null, null);
cursor.moveToFirst();
return cursorToLocation(cursor);
}
private Location cursorToLocation(Cursor cursor) {
Location location = new Location();
location.setId(cursor.getLong(0));
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
location.setAccuracy(cursor.getFloat(3));
location.setCreationTimestamp(Timestamp.valueOf(cursor.getString(4)));
return location;
}
也许我应该用约会代替?但这可能是格式的问题,不是吗?我找到了解决方案!事实上,时间戳是UTC,没有存储关于时区的信息 我的函数getDate现在与以下建议的解决方案类似:
Sqlite中的值是什么?emulator,您在哪里测试?如果是,请检查emulator的time.SQLite时间戳不包含时区信息。保存和加载时间戳的功能必须一致工作;显示它们。@JonSkeet在SQLite中,值是时间戳。示例:1397060298000,表示2014年4月9日20:18,但显示为18:18@伊莎:不,这是真手机,不是模拟器。
private String getDate(Timestamp timestamp) {
Calendar calendar = Calendar.getInstance();
TimeZone tz = TimeZone.getDefault();
calendar.setTimeInMillis(timestamp.getTime());
calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
SimpleDateFormat sdf = (SimpleDateFormat)SimpleDateFormat.getDateTimeInstance();
Date currenTimeZone = (Date)calendar.getTime();
String date = sdf.format(currenTimeZone);
return date;
}