SQL statement in Java to sort by date (month) - java

I have an SQL table in my Android project, that has a KEY_DATE field in Date format.
KEY_DATE + " DATE,"
My table is populated from the java code (date in dd/mm/yy format).
So now I need to make several date-related queries and something isn't working.
I need to make selections from a table for today, this month and this year.
Here's what I tried:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
Date todayD = new Date();
dateFormat.format(todayD);
String today = dateFormat.format(todayD);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
dateFormat.format(firstDay);
String selectQuery = "SELECT * FROM " + TABLE_PAYMENTS + "WHERE "
+ KEY_DATE +" BETWEEN " + firstDay + " AND " + today;
The query returns empty even though there's a lot of data for that period.
I believe something is wrong with data formats here. Can you help me to solve this?
Thank you in advance.

You are not formatting firstD, so you only get from the first day of the month at the current time on;
You should either use single quotes around the dates in your queries or use prepared statements, otherwise your server will understand your dates as math operations;
When querying for date ranges, remember that if you don't specify an hour with your date SQL will by default take it as zero hour (0:00:00.0000). If you use "between startDate and today", you get only midnight of today. If you use "between startDate and tomorrow", you get midnight of tomorrow too. You should use "date >= startDate and date < tomorrow" to get the proper range.
When writing queries with dates, I always prefer to use ISO format for the date strings: yyyy-MM-dd.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date todayD = new Date();
cal.setTime(todayD);
cal.add(Calendar.DATE, 1);
Date tomorrowD = cal.getTime();
String today = dateFormat.format(tomorrowD);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstD = cal.getTime();
String firstDay = dateFormat.format(firstD);
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE KEY_DATE >= '" + firstDay + "' AND KEY_DATE < '" + today + "'";

The problem is with the date formats for the data present inside the database and the date formats that you are passing (strings) to the sql query.
It is not a good practice to pass dates as string parameters to the sql query, so I strongly suggest use preparedStatement as shown below:
Date todayD = new Date();
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDay = cal.getTime();
String selectQuery = "SELECT * FROM TABLE_PAYMENTS WHERE BETWEEN ? AND ?" ;
//create preparedStatement here
preparedStatement.setDate(1, firstDay);
preparedStatement.setDate(2, todayD);

Related

How to fetch Records for a week

I am using Java 7 and fetching records for a week.For valid_from column I am subtracting -7 from current date below. The format of date in DB is 12-FEB-18. For valid_to column I am using sysdate. I am not getting correct valid_from date. Can anyone review this what is wrong here.
Format formatter = new SimpleDateFormat("dd-MMM-yy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -7);
Date todate1 = cal.getTime();
Date startdate = ((DateFormat)formatter).parse(formatter.format(todate1));
System.out.println(todayWithZeroTime);
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM >"
+ startdate+ " and a.VALID_TO > sysdate";
How can I parse only Date here. Currently I am getting Tue Feb 13 00:00:00 GMT 2018. I want 13-FEB-18 which I can send as variable in where condition.
Please suggest
You are converting a Date to a String then back to a Date.
Then you are using this Date object in your query, so it's toString() method gets called and yields a String representation which is probably not the one you wanted.
Avoid the last conversion from String to Date and just use
String startdate = formatter.format(todate1);
Note that you also have to escape the date string with quotes :
String sql_qry = "SELECT a.ACCOUNT_ID from tableName a where "
+ "a.STATUS_TYPE_KEY='ACTIVE' "
+ "and a.VALID_FROM > '"
+ startdate+ "' and a.VALID_TO > sysdate";
Also consider having a look at Java time API and at How to use PreparedStatement

How to find the days between dates using my code?

Below is my code which checks the date which is stored in database with the current system date and calculates the days and if that days is lesser than the 180 days it will print something else print nothing,this code works great in an normal java program(with out using swings concept) if it is used with the swing program i changed the sql query to check get the date from the database based on the department and staff names which is entered in the text fields,i coded this code inside an jbutton,in the output it just prints the current system date but not calculates the days between the selected date and the current system dates,friends this is the problem am facing kindly need your help friends....thanks in advance..
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/leave", "root", "");
Statement stm = conn.createStatement();
ResultSet rs = stm.executeQuery("select * from staff where depmt='" + txt1 + "' AND staffs='" + txt2 + "'");
Calendar javaCalendar = null;
String currentDate = "";
javaCalendar = Calendar.getInstance();
currentDate = javaCalendar.get(Calendar.DATE) + "/" + (javaCalendar.get(Calendar.MONTH) + 1) + "/" + javaCalendar.get(Calendar.YEAR);
int cdate = javaCalendar.get(Calendar.DATE);
int cmonth = (javaCalendar.get(Calendar.MONTH) + 1);
int cyear = javaCalendar.get(Calendar.YEAR);
int z = 0;
int date = 0, month = 0, year = 0;
System.out.println("Current Date\t" + currentDate);
System.out.println("\n");
while (rs.next()) {
date = rs.getInt(3);
month = rs.getInt(4);
year = rs.getInt(5);
System.out.println("Random Date\t" + date + "/" + month + "/" + year + "\n");
int d = (date - cdate);
int m = month - cmonth;
int y = year - cyear;
int d1 = java.lang.Math.abs(d);
int d2 = java.lang.Math.abs(m);
int d3 = java.lang.Math.abs(y);
z = d1 + (d2 * 30) + (d3 * 365);
if (z >= 180) {
System.out.println("something");
0
} else {
System.out.println("nothing");
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
//e.printStackTrace();
}
// TODO add your handling code here:
}
You should really use prepared statements cause this way your query is prone to sql injections.
Date formatter insted of concating string for currentdate
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = formatter.format(todaysDate);
Also it seems like your not closeing the connection that may be another issue.
Is there any reason for storeing the date in 3 separate columns?
Your algorithm to calculate the day difference between two dates is broken. It does not take in account different month lengths or leap years.
Unfortunately Java Calendar does not offer this feature at all. So either you apply your own homegrown algorithm (not easy, but in web there are some sources how to map a gregorian date to epoch days) or you use JodaTime like this way:
LocalDate db = new LocalDate(year, month, date);
int days = Days.daysBetween(db, LocalDate.now()).getDays();
Note that the result will be negative if db date is in the future. After all you can greatly shorten your code and abandon all Calendar stuff which is very bad for calculations of durations.
try this:
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("14/02/2014");
Date date2 = df.parse("08/03/2014");
int days = Days.daysBetween(date1, date2).getDays();
Try this, by changing return value from millisecond to day.
public static int daysBetween(Date dateFrom, Date dateTo){
return (int)( (dateTo.getTime() - dateFrom.getTime()) / (1000 * 60 * 60 * 24));
}
Start Of Day
If you start with a mid-afternoon date-time object, go back 180 days by calculating seconds * minutes * hours * 180, you'll end up excluding the date-times earlier in that day 180 ago whereas I suppose you would want to include them. You should pay attention to when the day begins.
Time Zone
Both the question and other answers ignore the issue of time zone. Time zone defines the beginning of a day. Given the point about start of day (above), time zone is a related component.
Avoid java.util.Date & .Calendar
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them. Instead use either Joda-Time or the new java.time package in Java 8.
Joda-Time
Here is some example code using Joda-Time 2.3.
Note that while a Joda-Time DateTime object is similar to a java.util.Date, a DateTime does truly know its own assigned time zone.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeInQuestion = new DateTime( 2013, 6, 5, 4, 3, 2, timeZone );
DateTime now = new DateTime( timeZone );
DateTime hundredEightyDaysAgo = now.minusDays( 180 ).withTimeAtStartOfDay();
boolean isExpired = dateTimeInQuestion.isBefore( hundredEightyDaysAgo );
Dump to console…
System.out.println( "dateTimeInQuestion: " + dateTimeInQuestion );
System.out.println( "now: " + now );
System.out.println( "hundredEightyDaysAgo: " + hundredEightyDaysAgo );
System.out.println( "isExpired: " + isExpired );
When run…
dateTimeInQuestion: 2013-06-05T04:03:02.000+02:00
now: 2014-03-10T07:34:26.937+01:00
hundredEightyDaysAgo: 2013-09-11T00:00:00.000+02:00
isExpired: true

How to convert a String to a Calendar object?

To store a Calendar object in SQLite database, i found that the easiest way is to convert the Calendar object to a string and store it in the database as text.
Now, the problem lies in extracting the stored date from the string.
How do I parse the string containing the Calendar object and set it to a Calendar value?
My code is:
String CREATE_DOCTORS_TABLE = "CREATE TABLE " + TABLE_DOCTORS + "("
+ KEY_ID_DOC + " INTEGER PRIMARY KEY," + KEY_DOCTOR_NAME + " TEXT,"
+ KEY_CLINIC_ADDRESS + " TEXT," + KEY_LAST_CHECKUP + " TEXT" + ");";
db.execSQL(CREATE_DOCTORS_TABLE);
where KEY_LAST_CHECKUP contains a value like this:
java.util.GregorianCalendar[time=?,areFieldsSet=false,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=4,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=198,DAY_OF_WEEK=4,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=19,SECOND=47,MILLISECOND=823,ZONE_OFFSET=19800000,DST_OFFSET=0]
and i've stored it in a database this way:
values.put(KEY_LAST_CHECKUP, (doctor.getLastCheckUpDate().toString())); // last check up date
Now, how do i retrieve the DAY, MONTH and YEAR from the stored string?
I read about how to convert a date string to a calendar object here:
How to convert a date String to a Date or Calendar object?
but my string is not just a date string. It contains a lot of other details too.
What is the best way forward?
Change your data model to use a Date. This is the usual type to be stored in the database.
You can set the Date to a Calendar by using
Calendar c = Calendar.getInstance();
c.setTime(date);
To retrieve the Date from a Calendar you can use
date = c.getTime();
Using a String to store a Date in a database needs formatting and parsing of the Strings and also no comparision iside the database can be done.
If you would like to keep string value in KEY_LAST_CHECKUP column. Try to use SimpleDateFormat.
If you keep long value, you don't need to use SimpleDateFormat.
For insert :
SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
String strDate = simpleFormat.format(doctor.getLastCheckUpDate());
values.put(KEY_LAST_CHECKUP, strDate);
For retrieve:
try {
String strDate = --> from DB
Date parsedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(strDate);
Calendar c = Calendar.getInstance();
c.setTime(parsedDate);
} catch (ParseException e) {
return "Unknown";
}

timestamp to date in java and get the count value

hi i have to convert timestamp to date after check the query and return the count value.
my database have date(1344399208,1344399269),status(Q,Q).
This is my code:
public class GetCurrentDateTime {
public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());
java.sql.Date date = new java.sql.Date(timeStamp.getTime());
System.out.println(date);
//count++;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date=CURDATE()");
ResultSet result = statement.executeQuery();
while(result.next()) {
// Do something with the row returned.
count++; //if the first col is a count.
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return count;
}
}
Here the date is saved in timestamp format.but i like to convert date(yyyy-mm-dd) format.its done successfully.ya i got the output is 2012-08-08.but i have to check the query today date+status=Q .so how is that date is save in variable and call that variable in query.so how is wrote query for above condition.after check the condition and display the returns count value on my tomcat console.How is to do.please help me
Partial Answer to your Question
Date Examples
Examples borrowed from Code Ranch and SO posts
// Get system time
Timestamp SysTime = new Timestamp(System.currentTimeMillis());
java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());
// Date + Time + Nano Sec
System.out.println(SysTime);
// Date + Time
System.out.println(UtilDate);
// Date
System.out.println(SQLDate);
Formatting Dates
// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);
Please note that I am new to java, hence verify if it works.
Comparing dates
See this SO post:
How to compare dates using Java
To convert date to the date format specified:
int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format
From what I understand from the edit, you want the query to be something like this:
PreparedStatement statement = con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");
I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.
From comments:
To get midnight date:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
To get all entries within a 24 period:
"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);

How to get the right week of year number through a Calendar?

guys,i am confused by invoking the following method:Calendar.getInstance().get(Calendar.WEEK_OF_YEAR),the result got from that method is not right.Here is my Code:
Locale.setDefault(Locale.CHINA);
Calendar calendar = Calendar.getInstance();
//we think Monday is the first day of a week in China,but not Sunday.
calendar.setFirstDayOfWeek(Calendar.MONDAY);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateString = "2010-01-01";
calendar.setTime(sdf.parse(dateString));
System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));
dateString = "2010-12-27";
calendar.setTime(sdf.parse(dateString));
System.out.println("DateString: " + dateString + ", week: " + calendar.get(Calendar.WEEK_OF_YEAR));
The result is
DateString: 2010-01-01, week: 1//This may be wrong?
DateString: 2010-12-27, week: 1//This result is definitely wrong.
So here is the question, how to get the right week of year number using Calendar instance?
The locale has only influence on formatting (i.e., parsing and formatting the date as Chinese). You need to set the timezone to China. Fix the Calendar#getInstance() line as follows:
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CST")); // China Standard Time
Try this:
Calendar calendar = Calendar.getInstance();
calendar.setMinimalDaysInFirstWeek(4);

Categories

Resources