TimeStamp Difference Between Java and SQLite - java

Hello I have and SLQLite database in which I have table water_logs
CREATE TABLE water_logs(
_id INTEGER PRIMARY KEY AUTOINCREMENT,
amount REAL NOT NULL,
icon INTEGER NOT NULL,
date INTEGER NOT NULL);
I store date in milliseconds.
Calendar cal = Calendar.getInstance();
cal.getTimeInMillis();
My problem is I want to get the day from the my date column using strftime function. The problem is tjat java calendar timestamp is different from SLQLite time stamp
1436859563832 --> result from cal.getTimeInMillis();
1436607407--> SELECT strftime('%s','now')
What I'm actually trying to do is to group records by day. The following SQL query works just fine if value of SELECT strftime('%s','now') is paste in the date column
SELECT SUM(amount), date(`date`) FROM water_logs
GROUP BY date(`date`, 'unixepoch')

Seems to me that you are using 2 different value types.
When you use
Calendar cal = Calendar.getInstance();
long time = cal.getTimeInMillis();
The output value is in Milliseconds, as described here.
While when you use
strftime('%s','now')
The output value is in Seconds, as described here.
So, that might be the cause for the mismatch between the two values.
Of course that the value in seconds might undergo some rounding which might change its value a little.

I will try to provide you the best way to store Dates in SQLite database.
1) Always use integers to store the dates.
2) Use this utility method to store the dates into the database,
public static Long saveDate(Date date) {
if (date != null) {
return date.getTime();
}
return null;
}
Like,
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, saveDate(entity.getDate()));
long id = db.insertOrThrow(TABLE_NAME, null, values);
3) Use this utility method to load date,
public static Date loadDate(Cursor cursor, int index) {
if (cursor.isNull(index)) {
return null;
}
return new Date(cursor.getLong(index));
}
like,
entity.setDate(loadDate(cursor, INDEX));
4) You can also order the data by date using simple ORDER clause,
public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC";
//...
Cursor cursor = rawQuery(QUERY, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
// Process results
}

Related

Sqlite and setting it between dates, Format Correct but still not working

So I'm trying to get a basic sql string to work where it will grab the records in the sqlite database based on between dates. However, for some reason, it doesn't work. I just don't understand why.
private void viewTransactionsBetweenDatesTable(){
//Sets the table to view transactions between certain dates
try{
//Get's the dates from startDateChooserTransactions1 and endDateChooserTransactions1
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("MMM dd, yyyy");
Date sdct = startDateChooserTransactions1.getDate();
Date edct = endDateChooserTransactions1.getDate();
String sdcts = df.format(sdct);
String edcts = df.format(edct);
String sdctlabel = df2.format(sdct);
String edctlabel = df2.format(edct);
//Child's ID
String cid = childIDCheck1.getText();
//Grab's the specified data and places that as the table
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND strftime('%Y-%m-%d', 'Report Transaction Date') BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
//Sets up the table
Info1.setModel(DbUtils.resultSetToTableModel(rs));
TableColumnModel tcm = Info1.getColumnModel();
//tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(10));
// tcm.moveColumn(11, 10);
// tcm.removeColum(tcm.getColumn(13));
//Changes modLabel1
modLabel1.setText(firstNameEditClass1.getText() + " " + lastNameEditClass1.getText() + " Between " + sdctlabel + " - " + edctlabel);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally{
try{
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am using a jdatechooser so I am sort of forced to use SimpleDateFormat compared to the better DateTimeFormatter. Anyway, I'm formatting it according to YYYY-MM-DD like sqlite likes, but when I run the function, the table does not display anything. I set the days pretty wide (Feb 01, 2018 to Feb 14, 2018) and the date in my database is Feb 07, 2018. I have a few records in the database for it to pull. However, it just doesn't do it. And no error is popping up, so I do not know why it is not working.
Image of the records that I'm trying to place into my jtable
Edit1: Before I forget, I also tried the following SQL string
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND 'Report Transaction Date' BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
This will not work:
strftime('%Y-%m-%d', 'Report Transaction Date')
because the format specifiers you have provided require that you supply three values, one each for year, month, and day.
If the dates in the database are stored as complete SQLite datetime strings, you will have to use
"... date([Report Transaction Date]) BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
Note square brackets (not single quotes) around column name. This has nothing to do with needing a date/time value, it's because the column name has spaces in it. Any column name with spaces has to be enclosed in double quotes or square brackets. That's why it's a good idea to never use spaces in column names.
If they are, in fact, stored as 'YYYY-MM-DD' strings, then the reason your alternative didn't work is because you single-quoted the column name 'Report Transaction Date', which results in comparing that literal string to the date values.

Cannot remove rows comparing dates in my SQLite db Android

I am trying and searching for a while now without success to remove specific rows in my db table.
I'd like to do this as a result in comparison between DATE record value and nextday value.
I thought this would do the work
String sql = "DELETE FROM Planned_expenses_table WHERE DATE <= date('now','+1 day')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(sql);
db.close();
But it did not.
Any suggestion? I am currently storing column DATE values with the pattern "YYYY-MM-DD" which is the same returned by date().
Logcat doesn't show any exception.
So what is wrong with this piece of code? Thank you in advance.
EDIT : i've just noticed that if i change <= in > the rows are deleted, but this is very strange since saved dates are older
I managed to achieve the hoped result.
Apparently i was saving the dates in the form YYYY-M-D instead of the one written in the question. Thats why the order check <= was misbehaving.
Why not calculate the date then pass in the actual value.
var tomorrow = DateTime.Now + TimeSpan.FromDays(1);
string sql = $"DELETE FROM Planned_expenses_table WHERE DATE <= '{tomorrow.ToString("yyyy/MM/dd")}')";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(sql);
db.close();

Storing unix timestamp in sql

I have a unix date in long format
Long tmpLong = (Long) local.getValue();
Here is the value of tmpLong
1485710457166
Now I want to store this variable inside of my SQLite DB, after some research I found out that you cant store Longs in SQLite so I tried this:
Long tmpLong = (Long) local.getValue();
Integer tmpInt = tmpLong.intValue();
But this gives me:
-348227250
In SQLite my datatype is INTEGER
I need help storing this unix number, any help is appreciated
Update 1
If I try store it as a long, so
localDB.add(image_id, unixTimestamp, PATH);
And then in my add method (inside SQLiteHelper class). I print the value for testing :
public void add(String image_id, Long date, String path) {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("SQL", "date " + date);
It prints 1
D/SQL: date 1
Well, that is what will happen when you truncate a 64 bit Long into a 32 bits integer...
Dont do that but try to store it like it is (as a long) because SQLite ints can handle that values, take a look into the Datatypes In SQLite
Edit:
Your code below:
public void add(String image_id, Long date, String path) {
SQLiteDatabase db = this.getWritableDatabase();
Log.d("SQL", "date " + date);
}
if that code is so as it is posted then you are passing as parameter 1 for the date value... the method this.getWritableDatabase(); is not going to modify/change the value of the date parameter...

How to get date value from SQLite in java

I have a simple table in my database:
CREATE TABLE [InformacjeZDziekanatu] (
[_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[DataWstawienia] DATE NOT NULL,
[DataModyfikacji] DATE NOT NULL,
[Tresc] VARCHAR2 NOT NULL);
In my application only what I want to do is to get value of DataWstawienia column.
I am using such method:
try {
ResultSet result = stat.executeQuery("select * from InformacjeZDziekanatu order by _id desc limit 5");
int id;
Date dataWst;
Date dataMod;
String tresc;
for(int j = 0 ; j < 5 ; j++) {
result.next();
Object[] lista = new Object[4];
id = result.getInt("_id");
dataWst = result.getDate("DataWstawienia");
dataMod = result.getDate("DataModyfikacji");
tresc = result.getString("Tresc");
lista[0] = id;
lista[1] = dataWst;
lista[2] = dataMod;
lista[3] = tresc;
dane[j] = lista;
}
}
All dates in DataWstawienia column are today's dates but using this method above I get 1970-01-01 date all the time.
What did I do wrong?
SQLIte does not have a DATE data type. Dates need to either be stored as integers (number of seconds since Unix Epoch is common) or as ISO 8601 times (e.g. 2013-10-01T12:12:12). If you say DATE in your SQLite schema you will store values as strings. Your solution of changing the type of dateWst to String acknowledges the fact that you are storing dates as strings and not as an internal date type.

Hibernate / Java Object can not be converted to a Date

I have the following method in my java. For some reason when I try and cast l_month as a Date it says that the object can not be cast. In my sql statement I convert the date to just be the month using the DATE_FORMAT with '%M', so it just returns a list of month names and the number of logins for that month. How can I get that l_month field to become a Date. Ultimately I am changing it to a string so if it could be cast to a string that would be great also but nothing seems to be working.
public List<Logins> getUserLoginsByMonth() {
Session session = getSessionFactory().openSession();
ArrayList<Logins> loginList = null;
try {
String SQL_QUERY = "SELECT l_date as l_month, SUM(logins) as logins FROM (SELECT DATE_FORMAT(login_time, '%M') as l_date, COUNT(DISTINCT users) as logins FROM user_logins WHERE login_time > DATE_SUB(NOW(), INTERVAL 1 YEAR) GROUP BY DATE(login_time)) AS Z GROUP BY(l_month)";
Query query = session.createSQLQuery(SQL_QUERY)
query.addScalar("l_month")
query.addScalar("logins");
List results = query.list();
for(ListIterator iter = results.listIterator(); iter.hasNext() ) {
Objects[] row = (Object[])iter.next();
System.out.println((Date)row[0}]);
System.out.println((BigInteger)row[1]);
}
}
catch(HibernateException e) {
throw new PersistenceDaoException(e);
}
finally {
session.close();
}
}
DATE_FORMAT is
Blockquote Formats the date value according to the format string.
So it's a string not date.

Categories

Resources