【发布时间】:2020-05-28 10:58:27
【问题描述】:
我将日期作为字符串存储在我的数据库中。这在使用 MySQL 时效果很好,但是在 android 中使用 room 我无法正确搜索查询中的日期和日期,因为 room 无法识别字符串日期。我想知道是否可以使用类型转换器将字符串简单地转换为长字符串。而不必重做我的整个数据库来存储日期而不是字符串,然后将日期转换为长。
我们将不胜感激。
/**
* Method used to gain the current date.
*
* @return
*/
private Date currentDate() {
calendar.add(Calendar.DATE, 0);
return calendar.getTime();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
String dateTimeOfWorkout = dateFormat.format(currentDate());
我知道了:
@TypeConverter
public static Date fromTimestamp(String value) {
if (value != null) {
try {
return df.parse(value);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
} else {
return null;
}
查询
// Get Monthly Logs
@Query("SELECT checkInTable.checkInId, checkInTable.moodBeforeId, " +
"checkInTable.checkInEntry, checkInTable.checkInEntry2, " +
"checkInTable.userId, moodBeforeTable.workoutDate,
moodBeforeTable.moodBefore, " +
"moodBeforeTable.moodBeforePK " +
"FROM checkInTable " +
"JOIN moodBeforeTable " +
"ON checkInTable.moodBeforePK = moodBeforeTable.moodBeforePK " +
"WHERE moodBeforetable.workoutDate >= datetime('now', '-1 month') " +
"ORDER BY moodBeforeTable.workoutDate DESC")
LiveData<List<CheckInLogsPojo>> getCheckInLogsMonthly();
型号
@NonNull
@ColumnInfo(name = "workoutDate")
@TypeConverters({TimeTypeConverter.class})
private String workoutDate;
更新:使用上述类型转换器和查询,它仍然没有对 1 个月的结果进行排序。它只是显示一切。
【问题讨论】:
-
你能发布你的字符串的示例格式吗?
-
你能准确地说明你的日期是如何形成的吗?一个样本。
-
将字符串的格式添加到问题中
标签: android android-room