How to Select Date in SQLite - sqlite

I have a problem with SQlite for DateTime in UWP-app.
Assume the SQLite DB has the following data:
PurchaseDate (Date in SQLite format)
-----------------------------------
2016-09-10 11:10:10
2016-09-10 11:10:15
2016-09-10 11:10:30
Pass in this Date:
strSQLiteDate ="2016-09-10"
I just want to check if there is any row in the tblPurchase.
There is no match from below SQL-Select. What did I miss? Did I miss the hh:mm:ss part? But I just need to check the yyyy-mm-dd part.
using (var db = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), DBPath))
{
var query = db.Query<tblPurchase>("Select * From tblPurchase where PurchaseDate = " + " date('" + strSQliteDate + "')");
intcount = query.Count;
if (intcount != 0)
{
return intcount;
}
}
Edit 1
10/8/2016 10:13:26 AM
The above date will be recreated as DateTime and SQLit.Net-PCL use it to insert into SQLite DB
string[] strAr_Date = strDate.Split('/');
string strYear = strAr_Date[0].ToString();
string strMth = strAr_Date[1].ToString();
string strDay = strAr_Date[2].ToString();
string strDateTime = strDay + "/" + strMth + "/" + strYear + " " + strTime;
DateTime dt = DateTime.Parse(strDateTime);

... where PurchaseDate = date('2016-09-10')
The date() function removes the time portion from a date/time value.
But the value 2016-09-10 does not have a time portion, so it is not changed.
The PurchaseDate values still have the time portion, so you end up with a comparison like this:
... where '2016-09-10 11:10:10' = '2016-09-10'
You have to remove the time from the PurchaseDate values:
... where date(PurchaseDate) = '2016-09-10'

Related

Getting data according to last hours from sqlite

I want to get records out of sqlite database according to hours. following are my questions
1) I have to extract all data from sqlite for past one hour. I have tried following query but it provide me data for all the hours in present day
Query:
SELECT * FROM Table1 where Date >= datetime('now','-1 hours')
Where Table1 is my table name and Date is coloumn name of type DATETIME
Eg: there are following record in database
When I fire query in sqlite firefox browser tool it returns me
which I do not want.
What should be the query to get past 1 hour data from database
2) What should be query to get the value out of database according to every hours, like I have to get data for past 1 hour, then data of past 1-2 hour, the data of past 2-3 hour i.e an hour data between two hours?
Any Help will be appreciated.
Use this query for question 1 -
`select * from Table1 where(Date between '(Select Date from Table1 order by Date asc limit 1)' and 'date1');`
date1 should be in formate yyyy-MM-dd hh:mm:ss(for example 2015-10-21 08:00:00).
In date1 you can put before 1 hour datetime.
it is working in SQLite Manager.
For question 2 -
you have to get data for every hour separately using below query
select * from Table1 where(Date between 'date1' and 'date2');
Finally I found the solution to my own question
Following is the code which worked for me
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
Calendar calendar = Calendar.getInstance();
String startDate = dateFormat.format(date);
String endDate = "";
for (int i = 1; i <= 24; i++) {
System.out.println("Start Date:- " + startDate);
calendar.add(Calendar.HOUR_OF_DAY, -1);
date = calendar.getTime();
endDate = dateFormat.format(date);
System.out.println("End Date:- " + endDate);
String data = dbAdapter.getOutDoorHourlyData(startDate, endDate);
System.out.println("Hourly Average:- " + data);
startDate = endDate;
endDate = "";
}
public String getOutDoorHourlyData(String startDate, String endDate) {
double outdoorHourly = 0;
Cursor cursor = _sqliteDB.rawQuery("Select AVG("
+ COLOUMN_NAME + ") from (Select * FROM "
+ TABLE_NAME + " where " + COLOUMN_NAME + " >= '"
+ endDate + "' and " + COLOUMN_NAME + " < '" + startDate
+ "')", null);
try {
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
do {
outdoorHourly = cursor.getDouble(0);
} while (cursor.moveToNext());
}
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
String hourlyData = decimalFormat.format(outdoorHourly);
hourlyData = hourlyData.replace(",", ".");
return hourlyData;
}
}
I hope it will help someone in future

How to filter data from database based on YYYY-MM using Selection and SelectionArgs[] parameter in Android SQLite Query

I am storing YYYY-MM-DD and HH:MM:SS values in two separate columns in all my SQLite tables.
I have been using the following code to filter data by supplier id and date from my SQLite database.
public double addPurchaseTotal(String supplierID, String date) {
SQLiteDatabase db = helper.getReadableDatabase();
double result = 0;
String selection = VivzHelper.COLUMN_ADD_PURCHASE_SUPPLIER_ID + " =? "
+ " AND " + VivzHelper.COLUMN_ADD_PURCHASE_DATE + " =? ";
String[] selectionArgs = {supplierID, date};
Cursor c = db.query(VivzHelper.ADD_PURCHASE_TABLE,
new String[]{"sum(" + VivzHelper.COLUMN_ADD_PURCHASE_ITEM_COST_PRICE + ")"},
selection,
selectionArgs,
null,
null,
null);
if (c.moveToFirst()) {
result = c.getDouble(0);
}
c.close();
return result;
}
The value for date parameter is obtained from a date picker. As mentioned earlier, date value under the VivzHelper.COLUMN_ADD_PURCHASE_DATE is stored in YYYY-MM-DD format. I would like to filter my data based on YYYY-MM (year and month alone). How can this be done?
Instead of comparing the entire string with =, check for the prefix with LIKE or GLOB:
... WHERE Supplier = 'xxx' AND Date LIKE '2015-04-%'
... WHERE Supplier = 'xxx' AND Date GLOB '2015-04-*'
(GLOB works better together with indexing.)
In Java:
String selection = ...
+ " AND " + VivzHelper.COLUMN_ADD_PURCHASE_DATE + " GLOB ?";
String[] selectionArgs = { ..., date.substring(0, 8) + "*" };
I guess you are looking for this: SQLite Date and Time Functions

Datediff not returning expected value

this code always return '0' i don't know why
Dim cur_month = DatePart(DateInterval.Month, Now).ToString()
Dim cur_date As String = "01/" + cur_month + "/" + (DatePart(DateInterval.Year, Now).ToString)
Dim sel_date As String = "01/" + (cmb_mnth.SelectedIndex + 1).ToString + "/" + txt_year.Text.ToString
Dim date_dif As String = DateDiff(DateInterval.Month, CDate(sel_date), CDate(cur_date))
MsgBox(date_dif)
cnb_mnth is ComboBox for Month
txt_year is Text Box For Entering Year
I'd guess that the regional date settings on your computer has month before day (i.e., MM/dd/yyyy), so it interprets 01 as the month for both cur_date and sel_date.

VB.net - CDate with SQL

I'm doing the following query to check if the current month is the same as the SQL field "Start".
If Today.Month = CDate(rsData("Start")).Month Then
What I'd like to do is switch it so that it will check within a 30 day period rather than identify the current month? Any ideas on how to do this?
If Date.Today.AddDays(-30) >= CDate(rsData("Start"))
' start date not older than 30 days '
End If
or if you have a variable date:
var minBoundary = New Date(2011,1,1)
var maxBoundary = New Date(2012,1,1)
var startDate = CDate(rsData("Start"))
If startDate >= MinBoundary AndAlso startDate <= maxBoundary
' start date between two dates '
End If
I believe in this case you would want to use the AddDays method of DateTime.
Dim mydate as DateTime = CDate(rsData("Start"))
Dim checkdate as DateTime = mydate.AddDays(30)

Using BETWEEN in a DataTable.Select

I thought this would be simple but obviously not!
Basically, I have a date and want to do a 'between' on two date columns like this:
myDataTable.Select(myDate & " between (StartDate and EndDate)")
Where StartDate and EndDate are date columns that do exist in the DataTable.
Any ideas?
Why not just use >= and <=
Dim dt As New DataTable()
dt.Columns.Add("StartDate")
dt.Columns.Add("EndDate")
Dim row1 As DataRow = dt.NewRow()
row1("StartDate") = New DateTime(2009, 1, 1)
row1("EndDate") = New DateTime(2009, 1, 31)
dt.Rows.Add(row1)
Dim myDate As New DateTime(2008, 12, 15)
Dim rows As DataRow() = dt.[Select]([String].Format("#{0}# >= StartDate AND #{0}# <= EndDate", myDate.ToString("dd MMM yyyy")))
The DataTable.Select method doesn't support the BETWEEN operation. This operation is specific to a database engine. Remember that the DataTable is an in-memory construct and doesn't necessarily support all the features of a database server.
The DataTable.Select method supports the same filter expression syntax as DataColumn.Expression. You can try the following expression to achieve the same thing (note I haven't tested this!):
myDataTable.Select("#" + myDate + "# >= StartDate AND EndDate <= #" + myDate + "#");
Be carefull, first you have to write column name then the condition and at the end it goes the variable:
myDataTable.Select( **StartDate** =< "#" + myDate + "# AND **EndDate** <= #" + myDate + "#");

Resources