user8452856
user8452856

Reputation: 45

Compare java getTime time with strings representing a date

I have stored the date of a specific method each time it gets executed in ab sqlite database in 3 columns (one for the day, the month and the year).

Now I want to compare it to the date of the actutal day the user uses the app. With

Date currentTime = Calendar.getInstance().getTime()

I get this date, but how am I able to compare it to the strings I get from my database? Thank you!

Upvotes: 0

Views: 51

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 340350

Using java.time

Your Question is a duplicate of many others. So briefly…

Use java.time classes rather than the troublesome old legacy date-time classes. For Android, use libraries from the ThreeTen-Backport and ThreeTenABP projects.

Get today’s date.

ZoneId z = ZoneId.of( "America/Montreal" ) )
LocalDate today = LocalDate.now( z );

Get to parts of the date.

int y = today.getYear() ;
int m = today.getMonthValue() ;
int d = today.getDayOfMonth() ;

Query the database.

myPreparedStatement.setInt( 1 , y ) ;
myPreparedStatement.setInt( 2 , m ) ;
myPreparedStatement.setInt( 3 , d ) ;

As others suggested, you should be using date-time types in your database to store date-time values rather than mere ints for the pieces.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 1

Lukas Schröder
Lukas Schröder

Reputation: 344

Try this:

SimpleDateFormat formattedDate = new SimpleDateFormat("dd/MM/yyyy");  
String strDate= formattedDate.format(date);  

It will give you your date as shown in the Template. Now simply build a String out of your SQLite data in the same way (dd/MM/yyyy) and you cam simply compare them like shown in this post: https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

Upvotes: 0

Related Questions