Reputation: 121
Am trying to get datetime difference with joda time (ie startdate -2014-02-26 and enddate-2014-02-26) for a day but i keep on getting a blank table.When i change to startdate -2014-02-26 and enddate-2014-02-27 data gets displayed. below is sample code
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date todaydate = new Date();
DateTime jodaToday = new DateTime(todaydate);
String datefrom = sdf.format(jodaToday.toDate());
String dateto = sdf.format(jodaToday.plusDays(1).toDate());
and my query looks like below.
ProductTable.setContainerDataSource(storeData(
"SELECT * FROM sales where sale_time BETWEEN '"
+ datefrom + "' AND '" + dateto + " ' ORDER BY sale_time DESC"
));
What could i be missing ?
NOTE: When i do a test with the below query i get data
SELECT * FROM sales WHERE sale_time BETWEEN
'2014-02-26 00:00:00' AND '2014-02-26 23:59:59' ORDER BY sale_time DESC;
Thanks
Upvotes: 1
Views: 168
Reputation: 121
The below is the solution that worked. Note added timestamp(23:59:59) in bold.
" AND sale_time >= '"+sdf.format(fromdate.getValue())+"' AND sale_time <= '"+sdf.format(Todate.getValue())**+" 23:59:59'"**;
Upvotes: 0
Reputation: 2510
Data from midnight to midnight:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTime from = new DateTime(2014, 2, 26, 0, 0).withTimeAtStartOfDay();
DateTime to = from.plusDays(1).withTimeAtStartOfDay().minusSeconds(1);
String datefrom = sdf.format(from.toDate());
String dateto = sdf.format(to.toDate());
EDIT
Maybe the extra space is the problem:
...dateto + " ' ORDER BY...
^
Upvotes: 2
Reputation: 85779
Your problem is more about understanding the BETWEEN
SQL statement. In simple words, BETWEEN
can be explained as:
FOO BETWEEN A AND B
Which is equivalent to
FOO >= A AND FOO <= B
With this in mind, if you have sale_time >= '2014-02-26' AND sale_time <= '2014-02-26'
, it will be understood by your database engine as sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-26 00:00:00'
. So, the database engine won't be able to find a row which sale_time
value is '2014-02-26 05:32:16'
or similar.
After understanding this, then you're able to understand why setting the second parameter of your between works when you add one day to today. The SQL statement would be:
sale_time BETWEEN '2014-02-26' AND '2014-02-27'
Which can be understood as:
sale_time >= '2014-02-26 00:00:00' AND sale_time <= '2014-02-27 00:00:00'
I don't know vaadin but you should use a method where you will send these String
s as parameters rather than concatenating them to generate the query to execute. Note that if you do this more and more your application is prone to SQL Injection.
Upvotes: 2
Reputation: 4328
Little bit difficult to give an answer without the Table and data,
Upvotes: 1