0

Im getting timeStamp from Sqlite like this:

"timestamp" + " TIMESTAMP DEFAULT CURRENT_TIMESTAMP );"

This is how i get the date: 2019-06-23 04:25:28 and i'm transforming to get the days and im getting this 18070 and not the int day

String timestamp = cursor.getString(cursor.getColumnIndex(VentasContract.TIME_STAMP));
                Log.d("TIEMPO",timestamp);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = sdf.parse(timestamp);
                long millis = date.getTime();
                long days = (millis / (60*60*24*1000));
                Log.d("DIA",String.valueOf(days));



  // The value of TIEMPO is 2019-06-23 04:25:28
  // The value of DIA is 18070

I expect the current day "23"

Akshit
  • 424
  • 4
  • 15
MADMVX
  • 354
  • 1
  • 4
  • 18
  • 2
    Don't use the old `SimpleDateFormat`, `Date` and `Calendar` classes, but classes from the package `java.time` instead. – MC Emperor Jun 23 '19 at 06:34
  • If it’s for (older) Android, consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use `java.time`, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Jun 24 '19 at 12:54

2 Answers2

2

tl;dr

myResultSet.getObject( … , OffsetDateTime.class ).getDayOfMonth() 

23

Details

Convert your legacy java.sql.Timestamp object to a modern java.time.Instant object rather than implicitly calling toString.

Instant instant = myTimestamp.toInstant() ;

Adjust to the time zone through which you want to perceive a date and time. Perhaps that is UTC itself.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

Extract the day of month.

int dom = odt.getDayOfMonth() ;

23

Tip: The terrible java.sql.Timestamp class was supplanted years ago with JDBC 4.2. We can now exchange modern java.time objects with the database.

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • Thanks this works but just with API > than oreo I think – MADMVX Jun 24 '19 at 03:24
  • @Dskato if you are concerned about Android, you should have mentioned it, and tagged your Question. For Android earlier than 26, see the *ThreeTen-Backport* and *ThreeTenABP* libraires. Both have been addressed many many times already on Stack Overflow. – Basil Bourque Jun 24 '19 at 06:40
1

Date#getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.

This is quite different from the day of the month.

You should use the Calendar class or switch to use the java 8 LocalDate class of java.time package.

Juan
  • 5,525
  • 2
  • 15
  • 26