I have a SQLite Database where I am getting data from all columns based on a given date eg. 30 Sep 2018. Where in COL2 I am saving dates in the same format.
Cursor inc_con_by_dat(String dat) {
SQLiteDatabase db = this.getWritableDatabase();
String que = "SELECT * FROM " + TABLE_NAME +
" WHERE " + COL2 + " = '" + dat + "'";
return db.rawQuery(que, null);
}
But now the COL2 Doesn't have the date format like 30 Sep 2018 anymore. cause I have decided to include data entry time in COL2 as well.
So I am saving COL2 in "EEE MMM dd HH:mm:ss Z yyyy" this format. But I am willing to change my "EEE MMM dd HH:mm:ss Z yyyy" format to anything that includes date and time. But I want to select columns only supplying like this example format "30 Sep 2018" or yyyy/mm/dd
So can anybody help me. or I just have to make another column for the time entry as well.
So I am saving COL2 in "EEE MMM dd HH:mm:ss Z yyyy" this format
Stop doing that. SQLite does not actually have a date column type, which means that your date information is being stored as literal text. Rather than trying to give you a workaround, I will just recommend that you always store your dates and timestamps in SQLite using an ISO format, something like:
YYYY-MM-DD HH:MI:SS
If you take this advice, then you would easily be able to compare another ISO date or timestamp against any record in your table. For example, if you wanted to find all records having a timestamp which fell on 2018-09-30, you could use this query:
SELECT *
FROM yourTable
WHERE ts >= '2018-09-30' AND ts < '2018-10-01';
Related
Unable to detect cause of application crash. Variables StartDate and lastTimeCalculateValues are long.
Cursor c = MyApplicationExtendsClass.database.rawQuery("SELECT * FROM " + MyApplicationExtendsClass.locationTableName + " WHERE [Date] >= '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).format(StartDate) + "' AND [Date] <= '" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US).format(lastTimeCalculateValues) + "' ORDER BY Id ASC", null);
Crash output from Google play console, 5% of active users and that is all I get.
android.database.sqlite.SQLiteException:
at android.database.sqlite.SQLiteConnection.nativePrepareStatement (Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement (SQLiteConnection.java:948)
at android.database.sqlite.SQLiteConnection.prepare (SQLiteConnection.java:559)
at android.database.sqlite.SQLiteSession.prepare (SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init> (SQLiteProgram.java:63)
at android.database.sqlite.SQLiteQuery.<init> (SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query (SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory (SQLiteDatabase.java:1493)
at android.database.sqlite.SQLiteDatabase.rawQuery (SQLiteDatabase.java:1427)
at my.packagename.MainActivity.calculateValuesFinalFromDb (MainActivity.java:4013)
at my.packagename.MainActivity.access$1800 (MainActivity.java:152)
at my.packagename.MainActivity$CalculateValuesTimer.run (MainActivity.java:4112)
at java.util.TimerThread.mainLoop (Timer.java:562)
at java.util.TimerThread.run (Timer.java:512)
SQLite docs for DateTime SQLite docs
A time string can be in any of the following formats:
YYYY-MM-DD
YYYY-MM-DD HH:MM
YYYY-MM-DD HH:MM:SS
YYYY-MM-DD HH:MM:SS.SSS
YYYY-MM-DDTHH:MM
YYYY-MM-DDTHH:MM:SS
YYYY-MM-DDTHH:MM:SS.SSS
HH:MM
HH:MM:SS
HH:MM:SS.SSS
now
DDDDDDDDDD
Documentation says yyyy-MM-dd HH:mm:ss.SSS can be used
Try to change
SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.US)
To
SimpleDateFormat("yyyy-MM-dd", Locale.US)
This is the default SQL format for dates.
And see my answer here: Can't get data from date to date SQLite
Update:
First part of your link:
SQLite supports five date and time functions as follows:
1. date(timestring, modifier, modifier, ...)
2. time(timestring, modifier, modifier, ...)
3. datetime(timestring, modifier, modifier, ...)
4. julianday(timestring, modifier, modifier, ...)
5. strftime(format, timestring, modifier, modifier, ...)
To get presicion in milliseconds you could use following conversion:
CAST((julianday('your_date') - 2440587.5)*86400000 As INTEGER)
Explanation:
julianday('your_date') returns number of days since noon in Greenwich on November 24, 4714 B.C.
julianday('your_date') - 2440587.5 returns number of days in Epoch time (1970)
*86400000 converts it to milliseconds (24* 60* 60* 1000)
Found here.
Then you can do Integer comparison with >= or also with BETWEEN .. AND ..
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
I am trying to create a date object(format : HH:MM) from a String Example 13:30(HH:MM). I want to save the HH:MM in MySql table but the below code enters some random value in the column (eg: '6828-00-00 00:00:00'). How can i store the date value in Mysql in the HH:MM format ?
Date date = null;
String afternoon = "13" +":" +"30";
String time = afternoon;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
e.printStackTrace();
}
long d = date.getTime();
java.sql.Date sqlDate = new java.sql.Date(d);
String sql3 = "CREATE TABLE IF NOT EXISTS DateTime"+
"(UniqueBusID VARCHAR(255) not NULL, " +
" Timenings DATETIME DEFAULT NULL ,"+
" PRIMARY KEY ( UniqueBusID ))";
stmt.executeUpdate(sql3);
stmt.executeUpdate("INSERT INTO DateTime " + "VALUES ('Test3','"+sqlDate.getTime()+"')");
EDIT
You have to use java.sql.Timestamp instead of java.sql.Date. As from javadoc,
"To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated."
So just replace the line
java.sql.Date sqlDate = new java.sql.Date(d);
with
java.sql.Timestamp sqlTime = new Timestamp(d);
You are doing it all right, except the pattern you have used to parse the String as Date i.e. HH:mm, which is wrong.
Correct Format : H:mm (H: 0-23; h:1-12)
try {
date = new SimpleDateFormat("H:mm").parse(time);
}
Here is the reference for Date and Time Patterns
I am surprised that it inserted '6828-00-00 00:00:00' :-)
Four problems here.
[1]
First that when you set a SimpleDateFormat, you're creating a java object Date. Java Date starts from Jan 1st 1970, so if you set only the hour and minute, the formatter will assume all other fields are zero (and not today), so
System.out.println(new SimpleDateFormat("HH:mm").parse("13:30")); // returns Thu Jan 01 13:30:00 BRT 1970
[2]
But then, you've called the getTime() method, which returns the millis since Jan 1st 1970
System.out.println(new SimpleDateFormat("HH:mm").parse("13:30").getTime()); //59400000
[3]
Then, you've tried to push this number into MySQL. MySQL datetime expects a string in the format
YYYY-MM-DD HH:MM:SS
(see https://dev.mysql.com/doc/refman/5.0/en/datetime.html)
Since MySQL is a very benevolent database ;-) it tries to convert 59400000 into this format, which obviously
mysql> insert into d values (59400000);
Query OK, 1 row affected (0.04 sec)
mysql> select * from d;
+---------------------+
| y |
+---------------------+
| 5940-00-00 00:00:00 |
+---------------------+
1 row in set (0.08 sec)
[4]
Of course, you could just adjust your SimpleDateFormat to MySQL expected date format, but you're concatenating strings in a INSERT query, and this is not a good idea for security reasons neither is efficient. Instead, you should use a PreparedStatement and set the Date object (not the millis)
I am trying to insert a dd/mm/yyyy date format into my database table. The data type for date column in database is date and my SQL insert statement is:
INSERT INTO sm_product(productName, productDescription, productPrice, productQuantity, productStatus)
VALUES ('" + name + "', '" + desc + "', " + price + ", " + quantity + ", 'Available', '" + date + "'";
However, netbeans shows me an error when I added the date variable into the SQL statement.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
And it stores the date as:
Wed Jun 19 17:42:26 SGT 2013
And I got my dd/mm/yyyy date format in user interface:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
dateFormat.format(date);
This format is not I wanted. So I wonder how should I amend my SQL statement to fix the problem.
Thanks in advance.
If you are using SQL Server , you can use
REPLACE(CONVERT(VARCHAR(11),date,105),'-','/')
If you insert following format sting into query, record will be updated
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
String formatDate = dateFormat.format(date);
Iam saving date in below format EEE MMM dd HH:mm:ss z yyyy, but it is saving in this format 2013-05-03 00:38:20.0. But when i print same date on console before saving to database, it is as expected INFO: Fri May 03 00:38:20 IST 2013
Please can anyone explain why it is saving as above mentioned.
Below is the code:
Date now = new Date();
String datetimeStr = now.toString();
SimpleDateFormat format = new SimpleDateFormat(
"EEE MMM dd HH:mm:ss z yyyy");
Date parseDate = format.parse(datetimeStr);
Datebase column
date_order_created date
I hope you're not actually saving your dates as text in the database in the first place. Assuming you're not (and I don't think you are), you're not really "saving date in below format" at all... you're just saving the date.
The value of a date doesn't have a format - June 19th 1976 is the same date whether I represent it that way, or as 1976-06-19 or 19/06/1976 or 06/19/1976 (assuming I know how to interpret any of those formats). That's what you're seeing here - you're saving the date, and when you look at it "in the database" (e.g. via some SQL console) you're seeing one representation... but when you fetch it from the database and print it from Java, you're seeing the results of calling Date.toString(). That doesn't change the value at all.
If you want to format a Date value in one particular way, use SimpleDateFormat - but be very aware that a Date object itself has no format (or time zone, or calendar) and your database probably doesn't either. (The exact details of what goes in the database will depend on the database and the column type.)
It's very important to distinguish between a value and string representations of that value.
For example, if I write:
int x = 0xff;
int y = 255;
System.out.println(x == y);
then that prints "true" - because both x and y have the same value. The fact that in one case I used a hexadecimal representation doesn't affect the value as a number at all.
From here
The following code formats a date and time according to the pattern String passed to the SimpleDateFormat constructor. The String returned by the format method contains the formatted date and time that are to be displayed.
Date today;
String output;
SimpleDateFormat formatter;
formatter = new SimpleDateFormat(pattern, currentLocale);
today = new Date();
output = formatter.format(today);
System.out.println(pattern + " " + output);
The following table shows the output generated by the previous code ex
Pattern Output
EEE, MMM d, ''yy Tue, Jun 30, '09
When you save a Date objet in a database, this is generally not its String representation which is saved. This depends of the field type used in the database.
And :
Fri May 03 00:38:20 IST 2013
looks like a date.toString()