简体   繁体   中英

How to get the number of days between a given date and the previous records date?

I have a ListView with records and tapping on a record opens a detailed record view. In this detailed view, I want to print out the number of days between the current record and the previous record. How can I do that?

I know there exist an SQLite function getting the last inserted id, but I can't see that it would help here.

I'm thinking of solving it this way:

  1. Get the id of the current record shown in detailed view
  2. Get its date and save temporarily
  3. Given that id, what is the id of the record written before current id?
  4. Given the id of the previous record, get its date and save temporarily.
  5. Calculate number of days between current record in detailed view and previous record.

So, the answer I want is like: this tank lasted for 13 days.

Actually I'm stuck on step 3 above, how can I find out, given an arbitrary id, what the record stored in the db before that id, has for id?

An example:

id  date  note
---------------------------
1   2013-01-03  first note
2   2013-01-13  second note
4   2013-01-20  ...
7   2013-02-01  ...

If I open the detailed view for record with id 4, I want to calculate the number of days gone since record with id 2 was written. Ie 2013-01-20 - 2013-01-13.

Kind regards, Ramon

You can use the following approach for date manipulation:-

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

long d1=formater.parse(date1Str).getTime();
long d2=formater.parse(date2Str).getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

You should not go by ID. Insert the timestamp while inserting record. Get the record order by timestamp.

Once you have ordered data, it is just matter of writing date difference function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM