0

In my android sqlite database there is a column that contains the timestamp in the format (2013-12-12 18:47:31) of the data. Now a particular data may have time stamp which is earlier than present day or later than present day. e.g. today its 20 December 2013, and database contains data of 1 November 2013, 6 November 2013, 12 December 2013, 1 January 2014 etc... Now I want to fetch data which are earlier than present day i.e. 20 December 2013. How to do that?

Rahul
  • 381
  • 1
  • 5
  • 19

5 Answers5

2
select [Columns] from [database] where [column_date] < "currentDate";

To get current date and time, check this link Get current time and date on Android

Community
  • 1
  • 1
Anatol
  • 941
  • 1
  • 7
  • 13
2

you can use the following query to fetch the data based on timestamp

SELECT [COLUMN 1], [COLUMN 2]...., [COLUMN N] FROM [TABLE] WHERE TIMESTAMP_FIELD < strftime('%s','now');

- Date And Time Functions

Else you can also fetch currentTimeStamp like this

SELECT [COLUMN 1], [COLUMN 2]...., [COLUMN N] FROM [TABLE] WHERE TIMESTAMP_FIELD <
CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000
AS BIGINT)

- Link for reference

Community
  • 1
  • 1
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
1

yyyy-MM-dd HH:mm:ss datetime stamps have the same lexicographical and chronological order. You can use operators such as < and > on the strings.

laalto
  • 150,114
  • 66
  • 286
  • 303
0
Time time = new Time();

time.setToNow();

OR

Date todayDate = new Date();

todayDate.getDay();

todayDate.getHours();

todayDate.getMinutes();

todayDate.getMonth();

todayDate.getTime();
Ravindra Kushwaha
  • 7,846
  • 14
  • 53
  • 103
Ishan_Deb
  • 11
  • 1
  • 3
0

I had this problem of fetching data using timestamps but to no avail after weeks i got a good solution.

  1. set column timestamp as text on your table
 public static final String CREATE_TABLE =
            "CREATE TABLE " + TABLE_NAME + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_INCOME + " INTEGER,"
                    + COLUMN_EXPENSE + " INTEGER,"
                    + COLUMN_TIMESTAMP + " TEXT"
                    + ")";
  1. get the date using new Date() and convert to string
 private String getDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
        Date date = new Date();
        return dateFormat.format(date);
    }
  1. Insert data in your table using the getDateTime() for the timestamp
ContentValues values = new ContentValues();

        values.put(DailyTransaction.COLUMN_INCOME, income);
        values.put(DailyTransaction.COLUMN_EXPENSE, expense);
        values.put(DailyTransaction.COLUMN_TIMESTAMP, getDateTime());
  1. Then your sqlite query will look like this:
"SELECT * FROM "+ TABLE_NAME + " WHERE " + ClassName.COLUMN_TIMESTAMP + " <"+ "'"currentDate'";
Bellatez
  • 1
  • 2