0

I have a String s date in following format 05-10-2020

I want to convert this String to Date in following format dd-MM-yyyy so I can use it in below query for my Sqlite db

SimpleDateFormat simpledateformat = new SimpleDateFormat("dd-MM-yyyy");
String s = app.getDate(); // returns "05-10-2020"
Date date = simpledateformat.parse(s);
String selectQuery = "SELECT * FROM User Where Date !=" + date;

But date is returns date in follwoing format Mon Oct 05 00:00:00 GMT+03:00 2020

5
  • What else did you expect? This is the correct date. Commented Oct 5, 2020 at 10:43
  • My date in db is of type DateTime I need to compare it with same data type which is also DateTime that what I'm trying to do. converting the String to Date object so I can compare the two.Correct me if I'm wrong Commented Oct 5, 2020 at 10:47
  • can you try simpledateformat.format(s); , just a thought Commented Oct 5, 2020 at 10:47
  • @aryanagarwal format() returns a String Commented Oct 5, 2020 at 10:49
  • As an aside consider throwing away the long outmoded and notoriously troublesome SimpleDateFormat and friends. See if you either can use desugaring or add 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. Commented Oct 5, 2020 at 17:58

3 Answers 3

3

You should use PreparedStatement with LocalDate as this:

LocalDate ld = LocalDate.parse(app.getDate(),DateTimeFormatter.ofPattern("dd-MM-uuuu"));
String selectQuery = "SELECT * FROM User Where Date != ?";
try (PreparedStatement ps = con.prepareStatement(selectQuery)) {
    ps.setObject (1, ld);
    // ...
} catch (SQLException e) {
    e.printStackTrace();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Why do I have to use PreparedStatement
@r_via to avoid SQL Injection and Syntax errors
@r_via - Check SQL Injection. Also, this answer teaches you another good thing try-with-resources.
0

You should use prepared statements for RDBMS work. From your third line on, try:

PreparedStatement selectQuery = connectionObj.prepareStatement("SELECT * FROM User Where Date != ?");

selectQuery.setDate(1, date);

ResultSet res = selectQuery.executeQuery();

res.next();

// manipulate the resultset to your heart's content

Comments

0

It will provide a lean solution. You can dynamically adjust it to your code.

String dateStr = "Mon Oct 05 00:00:00 GMT+03:00 2020";
 
DateFormat formatOne= new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
DateFormat formatSecond= new SimpleDateFormat("dd-MM-yyyy");
System.out.println(formatSecond.format(formatOne.parse(dateStr)));

You can use it at the relevant place in your project.

DEMO

1 Comment

My String is in the following format "05-10-2020" also the code above returns 04-10-2020 it should be 05-10-2020

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.