如何在月初和今天之间查询SQLite数据

时间:2016-03-16 20:22:12

标签: java android database sqlite android-sqlite

我有一个包含column_date的表,其中日期保存为String yyyy-mm-dd 我通过代码查询上周

    String query = "select * from table_name where e_date  >= date('now','-7 days') order by e_date DESC";

它工作正常,但如果我使用

    String query = "select * from expenses where e_date  >= date('now','-30 days') order by e_date DESC";

它给了我最后30天,但我需要的是从月的第一天到现在的当前月份。 任何帮助表示赞赏和感谢。

2 个答案:

答案 0 :(得分:2)

SQLite start of month函数有localtimedate() modifers,因此您只需执行

String query = "SELECT * FROM expenses WHERE e_date BETWEEN date('now','localtime','start of month') AND date('now','localtime') "

如果您想在Java中执行此操作,则可以使用SimpleDateFormat为今天和月初获取yyyy-MM-dd字符串。

然后假设e_date是类型TEXT,您可以使用字符串连接进行查询

String query = "SELECT * FROM expenses WHERE " + monthStart + " <= e_date AND e_date <= " + today;

或者,使用BETWEEN

String query = "SELECT * FROM expenses WHERE e_date BETWEEN " + monthStart + " AND " + today;

例如

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_MONTH, 1);
String monthStart = dateFormat.format(c.getTime());

c = Calendar.getInstance(); // reset
String today = dateFormat.format(c.getTime());

System.out.println(monthStart + " to " + today);

将于2016年3月16日开始运行

2016-03-01 to 2016-03-16

答案 1 :(得分:-1)

我之前尝试过使用我的Android应用程序,试试这个

final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
Calendar startCal = Calendar.getInstance();
startCal.set(Calendar.MONTH, month);
startCal.set(Calendar.DAY_OF_MONTH, 1);
Calendar endCal = Calendar.getInstance();
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM expenses  WHERE   date( e_date/1000,'unixepoch','localtime')   >= '" + (SDF.format(startCal.getTime())) + "'  And  date( e_date/1000,'unixepoch','localtime')   <= '" + (SDF.format(endCal.getTime())) + "'";
Cursor cursor = db.rawQuery(selectQuery, null);