1

I have an application in which every Sunday, it checks a MySQL database for data from the past week. I am trying to find out how to get the date String for each day of the past week. My obvious first attempt was:

Calendar calendar = Calendar.getInstance();

if(calendar.DAY_OF_WEEK == 7){

    java.sql.Date date = new java.sql.Date(calendar.getTime().getTime());

    String dates[] = new String[7];

    for(int i; i < 7; i++){
        dates[i] = date.substring(0,7) + date.substring(7, date.length());
    }

    // Now grab data from the database where the date corresponds with one of these.
}

Today, this would work. However, if it were the 1st through the 6th of a month, this would not work as it wouldn't account for the change in month. Is there a way to get around this. I'm sure somebody has done a similar thing. Thanks.

Riley Fitzpatrick
  • 869
  • 2
  • 16
  • 38
  • 1
    If you data is stored in the database as date types, then you should avoid using `String`s to represent them in your queries, favouring `PreparedStatement`s to bind the values to the parameters. If the data is not stored as date types - then you have a much larger issue at hand. You should also consider using the new and improved date/time API available in Java 8+ – MadProgrammer Feb 10 '19 at 23:50
  • I do have it stored as a date type in my database, but I didn't know how else to manipulate a date. I figured it would be put into a prepared statement anyways so it wouldn't matter whether String or Date. – Riley Fitzpatrick Feb 11 '19 at 00:14
  • I recommend you don’t use `Calendar` and `java.sql.Date`. Those classes are poorly designed and long outdated. Instead use `LocalDate` from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). I also recommend you don’t pass strings to your database query. Use `LocalDate` there too. – Ole V.V. Feb 11 '19 at 08:17

1 Answers1

2

Can you try different approach? like pass today's date to sql procedure and filter last 7 days at query level with where clause?

say where date is <= today-7

Ashif Nataliya
  • 912
  • 2
  • 13
  • 28