Retrieve SQLite Data by using Date part out of DateTime Format - android

I want to retrieve the date from sqlite by using date. But by default the column in sqlite inserted is datetime format.
For instance,this is my Type Table
_id date_value
1 2015-07-06T11:36:35
2 2015-07-06T12:10:10
3 2015-07-06T12:10:19
4 2015-07-03T17:13:59
5 2015-07-03T17:14:04
6 2015-07-03T17:14:27
I want to retrieve the data by using date only. How do i want to query?
I tried to retrieve like this: Select * from Type where date_value=date('2015-07-03T17:13:59')
It returns zero rows.
I need all rows where the date(2015-07-03) matched
Expected result:
_id date_value
4 2015-07-03T17:14:27
5 2015-07-03T17:14:04
6 2015-07-03T17:14:27
How should i achieve this output?

The date() function simply returns the date part of its parameter, so the result of date('2015-07-03T17:13:59') is '2015-07-03'. This value does not match any of the values in the date_value column.
You need to extract the date from the values in the date_value column:
Select * from Type where date(date_value) = '2015-07-03'

Use SimpleDateFormat to format the Date as a String:
DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD hh:mm:ss");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
2015-07-03 16:14:27
2015-08-03 16:14:27

Related

How to retrive all the data from sqlite according to the date

I am Facing a problem in a query.In which i retrive the data from database according to the date like if todays date is 17/09/2016 i want all the data which is saved on this date the problem is when i retrive its show me only one data and there are many data present in my database i cant get out from this problem.
i know that it is a silly question but i am stuck in that from 2 to 3 days.
sqLiteDatabase.rawQuery("SELECT * from mytable where Date = (select max(Date) from mytable WHERE Date < DATE('now') );", null);
Cursor c = sqLiteDatabase.rawQuery("SELECT * from BluetoothDevice WHERE Date = date('now');", null);
while (c.moveToNext()) {
Date date = new Date();
date.setTime(Long.valueOf(c.getString(c.getColumnIndex("Date"))));
result.add(
new BluetoothDevice(
c.getString(c.getColumnIndex("Device")),
c.getString(c.getColumnIndex("Address")),
date
)
);
}
c.close();
return result;
}
That query would never retrieve TODAY's data. date('now') will always be now, so Sep 16, 2016. You then query for anything BEFORE (<) that day, so you only get records Sep 15, 2016 and earlier. You then take the MAX of those earlier dates, which can never be HIGHER than Sep 15 (because that's what your where specifies) and use an equality test on that.
So effectively, for a query on Sep 16th, you're running where date = 'Sep 15'
Why can you just have
SELECT ... WHERE date = date('now')
?

Android - Time Comparison "hh:mm:ss a" format

"I try to compare two time in "hh:mm:ss a" format. But it not really work in what I think. I googled but couldn't find a proper answer. Sorry cause I'm new to programming."
I try to compare the time like this:
String strSQL = "SELECT * FROM " + TABLE_SCHEDULE + " WHERE lecturer_id=? AND schedule_day=? AND schedule_endtime > ?";
schedule_endtime > ?
However, the comparison has ignored the AM/PM which caused the result become like this:
eg. 12:00:00 PM is bigger than 02:00:00 PM.
Hope that you all can give some tips or provide some solution. Appreciate it.
Instead of comparing the formatted string, compare the value in milliseconds. Take a look at this to convert the string back to date:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Then once you have two dates you can compare them like so:
boolean before = someDate.before(anotherDate);
or
boolean after = someDate.after(anotherDate);
or even
someDate.getTime() < anotherDate.getTime();
Side note: when I store dates, I like to just store the millisecond value and the time zone. That way you don't need to worry about things like this.
Inside the SQLite database you are storing the dates as Strings, not as a Date because in SQLite doesn't exist a Date type (https://www.sqlite.org/datatype3.html).
You have two options: change the column type to a INTEGER type and store de date as a number (then you can compare milliseconds) or get the entity as it is, parse a Date type with the String, create a SimpleDateFormat with the given format and then make the comparison.

How do I only save date and not datetime in google datasource

I'm working on an android app with gae as backend. I have two queries around DateTime object com.google.gdata.data.DateTime
While inserting data, I only want to to insert date and not datetime. Here's current object creation and it saves both date and time.
stock.setDate(new DateTime(new Date()));
Also while retrieving stock object, where I have aggregated data, I want to group by date and not datetime. But as the data got stored as date and time, I'm getting group by datetime, where as I want date. What to do in such scenarios (yes, if we solve 1st problem this wont be required, but otherwise what should be done). My retrieval code is
List<AggregatedStock> execute = null;
PersistenceManager pm = getPersistenceManager();
Query query = pm
.newQuery(" select date, vehicleCode, vehicleSubCode, colorCode, sum(count) from Stock as AggregatedStock ");
query.setFilter(" updatedByDealer == " + dealer);
query.setGrouping(" date, vehicleCode, vehicleSubCode, colorCode ");
query.setOrdering(" vehicleCode desc ");
query.declareImports("import com.sandeepapplabs.dms.Stock");
try {
List<Object[]> results = (List<Object[]>) query.execute();
execute = new ArrayList<AggregatedStock>();
for (Object[] result : results) {
execute.add(new AggregatedStock((Date) result[0],
(String) result[1], (String) result[2],
(String) result[3], ((Long) result[4]).intValue()));
}
} finally {
pm.close();
}
return execute;
A Date is a single moment in time. It's a not a "day" that lasts 24 hours. When you call new Date(), you get a different moment - down to a millisecond - each time. Note that there is no difference here between Date and DateTime - the DateTime is simply a Date with a chronology.
You have three options if you want to use the "date as a day" to group your entities:
(a) Always set the date as a midnight (how to create a Java Date object of midnight today and midnight tomorrow?).
(b) Save it as new Date(), but extract the "day" portion or convert it into a String formatted to represent a calendar day before using it to group entities.
(c) Store and use dates as String values (i.e. "2014-12-24").
App Engine supports java.util.Date as a property. Complete list of supported value types can be found here

data manipulation using sqlite

i am working on data manipulation using sqlite.
how can i insert the datetime value in sqlite
i implemented the below code in my app.
it works,
SimpleDateFormat curFormater = new SimpleDateFormat("dd-MMM-yyyy",Locale.ENGLISH);
Date dateObj = null;
dateObj =curFormater.parse(txt_date_start.getText().toString());
SimpleDateFormat postFormater = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);
String newDateStr = postFormater.format(dateObj);
but I want to store as "2011-Jul-13 05:15 PM",ple give me example..
thanks in advance
in sqlite you dont have any data type as date or time.while creating the column u have to specify any one of the text,int or real data type.then while inserting make use of the date and time funcs of sqlite.
Create column in sqlite's table with type TIMESTAMP/DATE and put the date in UNIX timestamp.

Insert TimeStamp in SQLite for Android

I have the following fields
1> WorkName - Varchar
2> TimeStap
I wanted to create a Table with the above fields.
What will be the TimeStamp datatype
How can I insert timestamp values to the table.
What will the timestamp value while inserting data or how to fetch the timestamp.
I have worked on SQLite but don't have any experience on adding TimeStamp as a field to the table & adding values to that.
What kind of CREATE & INSERT statements should I use?
There are limited datatypes available in a Sqlite Database, so the one I find useful for dates is integer - this will accept long values (dynamically adjusts its size) so for dates store the milliseconds value of a date and the date can be easily reconsituted when reading the millisecond values back out of the database.
I create timestamp by this:
/**
*
* #return yyyy-MM-dd HH:mm:ss formate date as string
*/
public static String getCurrentTimeStamp(){
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentTimeStamp = dateFormat.format(new Date()); // Find todays date
return currentTimeStamp;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
You could use Java.sql.Timestamp class as the column datatype of your table in a SQL database.
Since SQLiteDatabase class doesn't support a put() method for Timestamp variables, use the getTime() method in the class to insert the corresponding milliseconds of that time as a long value.(SQLiteDatabase does have a put() method for long type)
Open this for the method reference.

Categories

Resources