Comparing the Date in Android - android

I am using SQLITE database and I store the date as a String. Now I want to compare both the string as a date. While I am using
String sqlQuery = "SELECT title,edate FROM lookup WHERE" + ((Date)df.parse("?")).getTime() + "<=" + date1.getTime();
c= db.rawQuery(sqlQuery,new String[]{"edate"});
it is giving error at run time. Please Tell me how can I compare two String as a Date.
Thank You
Deepak

You want numbers in order to compare easily. I recommend POSIX (or unix) time, which counts seconds since a fixed point in about 1970.
Use an SQLite strftime function to convert your string to POSIX epoch time (check out the %s option) http://sqlite.org/lang_datefunc.html
Then use the Java functions to get epoch time: http://download.oracle.com/javase/6/docs/api/java/util/Date.html#getTime()
"SELECT title, edate FROM lookup WHERE strftime(edate,'%s') < " + (Date1.getTime()/1000)

String formatString = "dd-MM-yyyy"; // for example
SimpleDateFormat df = new SimpleDateFormat(formatString);
Date date1 = df.parse(string1);
Date date2 = df.parse(string2);
if (date1.before(date2)) {
System.out.println("first date is earlier");
}

Related

Get the added/modified/taken date of the video from MediaStore

Where do I get the taken date of the video from MediaStore? I got the following fields from MediaStore.
MediaStore.Video.Media.DATE_MODIFIED
MediaStore.Video.Media.DATE_TAKEN
MediaStore.Video.Media.DATE_ADDED
Those fields returned seemly default values -
dateModified: 1477043336
dateTaken: 1477043336000
dateAdded: 1477043352
Formatted dates -
dateModified: 01/01/1970
dateTaken: 01/01/1970
dateAdded: 01/01/1970
I double checked the stock gallery > random video file and I do see the correct dates. I looked at the video columns in MediaStore and I didn't see any other columns which has correct dates.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String formattedDate = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
String dateModified = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
String dateTaken = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN) * 1000L));
String dateAdded = dateFormat.format(new Date(row.getColumnIndex(MediaStore.Video.Media.DATE_ADDED) * 1000L));
Log.d(TAG, "dateModified: "+dateModified);
Log.d(TAG, "dateTaken: "+dateTaken);
Log.d(TAG, "dateAdded: "+dateAdded);
Log.d(TAG, "dateModified: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_MODIFIED)));
Log.d(TAG, "dateTaken: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_TAKEN)));
Log.d(TAG, "dateAdded: "+row.getString(row.getColumnIndex(MediaStore.Video.Media.DATE_ADDED)));
//Just multiply it by 1000 to get correct date
fun convertLongToDate(time: Long): String =
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
DateTimeFormatter.ofPattern("dd MMMM yyyy").format(
Instant.ofEpochMilli(time*1000)
.atZone(ZoneId.systemDefault())
.toLocalDate())
} else {
SimpleDateFormat("dd MMMM yyyy").format(
Date(time * 1000)
)
}
Looking at the annotations on the interface, DATE_ADDED and DATE_MODIFIED are annotated as SECONDS since the epoch, rather than milliseconds. DATE_TAKEN however is annotated as milliseconds since the epoch.
This difference in annotation explains the differences in zeroes that CommonsWare's answer notes. It also guides usage:
Since date formatters usually expect timestamps in millis, you should multiply second values by 1000 first.
Here is a simple function to get actual result of date format.
public String getDate(long val){
val*=1000L;
return new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(val));
}
Those fields returned seemly default values
I do not know why your second one has three extra zeros at the end. But, using a Unix date converter site:
dateModified = 1477043336 = Fri, 21 Oct 2016 09:48:56 GMT
dateAdded = 1477043352 = Fri, 21 Oct 2016 09:49:12 GMT
And your dateTaken, without the zeros, is the same as dateModified. So, assuming you can figure out where your zeros came from (such as by randomly deciding to multiply the value by 1000L), you have valid timestamps.
Syntax for convert epoch to normal date in android as follows
long date=System.currentTimeMillis(); //current android time in epoch
Converts epoch to "dd/MM/yyyy HH:mm:ss" dateformat
Means 1477043336 = 21/10/2016 09:48:56
String NormalDate = new java.text.SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new java.util.Date(date));

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.

Working with date in sqlite on android

When I run this query in sqlite tools I have a correct answer but when I run this query in my android project it returns 0.
Do you know what is problem?
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar strDate = Calendar.getInstance();
Calendar dateAgo = Calendar.getInstance();
dateAgo.add(Calendar.DATE, -7);
String query1 = "SELECT sum(Income.Money) AS 'Report' " +
" FROM Income " +
" WHERE Income.[Date] > '"+dateFormat.format(dateAgo.getTime())+
"' AND Income.[Date] <= '"+dateFormat.format(strDate.getTime())+"'";
I checked all of my code but they don't have any mistake.
MM/dd/yyyy is not a valid Time String (see: https://www.sqlite.org/lang_datefunc.html).
Use this format: yyyy-MM-dd.

Joda DateTime object adding +1 hour

i have the following code:
Log.e(TAG, "startTime = " + startTime);
DateTime dateTimeStart = new DateTime(startTime);
Log.e(TAG, "dateTimeStart = " + dateTimeStart );
.
which when logged out produces the following:
startTime = 2014-10-30T12:00:00+00:00
dateTimeStart = 2014-10-30T13:00:00.000+01:00
.
Why is an extra hour getting added on to the original time?
edit
How can i remove the +1:00, i haven't specified that.
Thanks
DateTime is an object consisting of a date, a time, and a timezone. In your case, you took startTime and converted it into an equivalent DateTime using the default system timezone.
+01:00 means "this timestamp is in some UTC+1 timezone", so 12:00:00.000+00:00 means the same as 13:00:00.000+01:00
So your timestamp was created at 12:00 British time = 13:00 Central European time.
If you want the time in UTC, do
DateTime dateTimeStart = new DateTime(startTime, DateTimeZone.UTC);
Use split method.
String splitDateTime[]=dateTimeStart.split("\\+");
dateTimeStart=splitDateTime[0];
Default DateTime::toString() method returns date in format yyyy-MM-ddTHH:mm:ss.SSSZZ .
+01:00 and +00:00 are the timezone offsets (ZZ in date format).
So if you want to print date without timezone offset, you should use another format. E.g. with method DateTime::toString(String):
String dtFormat = "yyyy-MM-dd'T'HH:mm:ss";
Log.e(TAG, "startTime = " + startTime.toString(dtFormat));
...
Log.e(TAG, "dateTimeStart = " + dateTimeStart.toString(dtFormat ));

compare current system date&time with date that is stored in data&time base in android

how to compare current system time with time that is stored in data base in android?
i use this code:
public static long s ;
.
.
.
.
Time now = new Time();
now.setToNow();
String query = "SELECT Cart_ID,Cart_Date from Tbl_Cart where Cart_ID="+lastId+" ";
// String queryt = "SELECT Cart_Date from Tbl_Cart where Cart_ID="+lastId+" ";
Cursor c = db.rawQuery(query, null);
if (c != null && c.moveToFirst() ) {
s = c.getLong(0);
}
if(s==now.setToNow())
{
...
}
If yours stored time is in millisecond then you can compare with System.currentTimeMillis().
Also you can think carefully about comparing with '==' .Because long time changes so rapidly, its very difficult to getting match with System time.You can better look for less/greater or equal with some time frame.
This code is only for data you can do same for time also.
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
CalCurrentDate = Calendar.getInstance();
// that will pass cureent date .
Current_Date = dateFormat.format(CalCurrentDate.getTime());
Fetch Date & Time From DB Using SQL Query :
Current_Date : Current data and compare by this Query.
selectQuery = "SELECT * FROM MY_TABLE WHERE `Date`>='"+Current_Date+"'";
Now you can run this Query as rawQuery().
Its depend on how you store the data-time in your database.
If you store like date-time then you can take the individual object in to the calender and then compare it with the System.currentTimeMillis();
e.g:
Calendar start_time = new GregorianCalendar();
start_time.set(Calendar.HOUR_OF_DAY, sHour);
start_time.set(Calendar.MINUTE, sMinute);
then compare it with systemtime like
If(start_time.getTimeInMillis() <= System.currentTimeMillis())
OR
If you store the date-time in the times in Millis formate then you can directly compare it.
e.g:
if(yourTimes <= System.currentTimeMillis())
Hope it will help you.

Categories

Resources