我正在尝试从房间中当前星期和月份获取数据。我已经创建了一个当前的Day查询,并且可以使用,但其他查询则无效。
日查询(此查询有效):
@Query("SELECT * FROM expense_table WHERE day = strftime('%d', 'now')")
LiveData<List<Expense>> getExpensesDay();
周:
@Query("SELECT * FROM expense_table WHERE week = strftime('%W', 'now')")
LiveData<List<Expense>> getExpensesWeek();
月份:
@Query("SELECT * FROM expense_table WHERE month = strftime('%m', 'now')")
LiveData<List<Expense>> getExpensesMonth();
实体:
@Entity(tableName = "expense_table")
public class Expense {
@PrimaryKey(autoGenerate = true)
private int expenseId;
private String note;
private Double value;
private String type;
private Long dateLong = System.currentTimeMillis();
private String date = new SimpleDateFormat("MM/yyyy").format(new Date(dateLong));
private static Calendar cal = Calendar.getInstance();
private int month = cal.get(Calendar.MONTH);
private int week = cal.get(Calendar.WEEK_OF_YEAR);
private int day = cal.get(Calendar.DAY_OF_MONTH);
private int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
private String weekDay = new DateFormatSymbols().getWeekdays()[dayOfWeek];
答案 0 :(得分:1)
根据文档,strftime('%W', ...)
将一年中的一周替换为0,而Calendar.get(Calendar.WEEK_OF_YEAR)
将一年中的一周替换为1。同样,strftime('%m', ...)
将一年中的一周替换为1,而Calendar.get(Calendar.MONTH)
返回一年中的一周从0开始。
因此,尝试替换Entity
类中字段的计算:
private int month = cal.get(Calendar.MONTH) + 1;
private int week = cal.get(Calendar.WEEK_OF_YEAR) - 1;
代替
private int month = cal.get(Calendar.MONTH);
private int week = cal.get(Calendar.WEEK_OF_YEAR);