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
Related
I'm trying to see how I can compare if the new date is after the old date if so no data will be shown from the firebase database. I am having trouble with this because my app crashes when I test it I believe I'm doing something wrong. Can someone help me with this issues? Below is my code. Thanks in advance
//Code
if(dataSnapshot.exists()){
//progressBar.setVisibility(View.GONE);
for (DataSnapshot postsnapshot : dataSnapshot.getChildren()) {
UserInformation2 upload=postsnapshot.getValue(UserInformation2.class);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("M-dd-yyyy");
//String now = simpleDateFormat.format(new Date());
Date d=new Date();
String AdCreationDate = postsnapshot.child("created").getValue(String.class);
//SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd")
try {
Date new_date = simpleDateFormat.parse(String.valueOf(d));
Date old_date = simpleDateFormat.parse(AdCreationDate);
if(new_date.after(old_date)){
// Your time expired do your logic here.
Toast.makeText(getContext(), "Your data expired", Toast.LENGTH_SHORT).show();
}else{
myUploads.add(upload);
recyclerView.invalidate();
}
} catch (ParseException e) {
e.printStackTrace();
}
//simpleDateFormat.format(d);
//Date e=new Date(old);
}
linearLayoutWithoutItems.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
Stacktrace
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.tout, PID: 22667
java.lang.IllegalArgumentException
at java.util.Date.parse(Date.java:638)
Your error isn't in the comparison, it's in the String old = simpleDateFormat.format(new Date(Date.parse(AdCreationDate)));
Check the value of AdCreationDate it might not be compatible with a list of valid date formats that can be parsed, at the very least you can place AdCreationDate into a SimpleDateFormat and then parse that.
You need to change this logic. When working with dates it's always better to work with timestamp. This is easy to convert to date or anything else and also easy to compare between dates.
So, when you are saving your date to the database just save it as
long timestamp = date.getTime(); //this will return time in milliseconds
Then when you retreive the values from database, you don't even have to format them before checking which one is older. You can simply use this:
long database_timestamp = postsnapshot.child("created").getValue();
long current_timestamp = System.currentTimeMillis();
if (current_timestamp > database_timestamp) //this will check if current_timestamp has greater value then database_timestamp, if it has it means that it's date from later in time
Now you can simply convert that to date and use SimpleDateFormat to format it as you want:
Date new_date = new Date(current_timestamp);
SimpleDateFormat format = new SimpleDateFormaT("MM-dd-yyyy");
This also covers each hour, second, minut,e or anything else you need. So, this will also check if the current date is greater than the other one even if there is only a few seconds difference between them. Which means your data will be live. If you don't need this you can also avoid it by setting the hour, minutes, and seconds on the Date to 0.
It looks like the error is actually related to
Date new_date = simpleDateFormat.parse(String.valueOf(d));
If you comment out that line and then update the if statement to
if(d.after(old_date)){
You don't need to parse the new date as it's already a Date object. You only need to parse the date from your snapshot as it is a string.
I'd also change the new date variable d to something more meaningful as it well help the readability of the code and the Java standard for naming variables is to use camel case where the scond word is capitalised without an underscore i.e. 'oldDate'. It's good to get into the habit of following these conventions.
I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.
"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.
I want to have a search between specific dates. Say for example from the 1st of Aug 2012 to 13th Aug 2012. Search on this criteria gives me the entered value in the DB. If I make it 2nd Aug 2012, the query returns me null...Even weirder is that when I select 10th, 11th or the 12th Dates it works fine and gives me results...I have gone crazy trying to know where the issue could be and debug has not lead me any where....Help please?
/**query to get the details by giving all the dates/
public Cursor getName_Intime_Outtime_Date(String fromdate,String todate)
{
Log.d("pavan","in side the getnameintime out time date() of visistor adapter");
return this.db.query(DATABASE_TABLE_VISITOR,
new String[]{KEY_NAME,KEY_CHECKIN,KEY_CHECKOUT,KEY_DATE},
KEY_DATE + " BETWEEN ? AND ?",
new String[] {fromdate ,todate},
null, null, null, null);
}
Sqlite doesn't have a data type for dates. Probably you save your date as TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
I recommend you save date fields in your table as sqlLite datatype INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC, or as BIGINT (long java time version in miliseconds).
This way you would have a corect value returned when using BETWEEN with numbers.
EDIT
You can manage your date string from your query using date and time functions. This means you can still use your dates as strings, but performing casts to "DATE" using conversion functions when stringDates are used in sql WHERE clause.
try this, it is working for me, SELECT * FROM table_name
where substr(column_name,7)||substr(column_name,4,2)||substr(column_name,1,2)
between 'YYMMDD' and 'YYMMDD' , dates should be in reverse order eg: if date format is DD/MM/YY or DD-MM-YY , you can use 'YYMMDD'
Thank you guys for really looking into this...Finally solved this using idea found in this link https://groups.google.com/forum/?fromgroups#!topic/android-developers/Ey_4rBZx2t0%5B1-25%5D ....to summarize what I did was take a Calendar object, retrieve the current date using the Calendar object, the retrieved data is given to a simpledateformat object and comparisons to be made on that....Here is the sample code...
int test = date_pick.getMonth()+1;
Toast.makeText(getBaseContext(), "Date seleted month"+test+"/"+date_pick.getDayOfMonth()+"/"+date_pick.getYear(), Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, date_pick.getYear());
cal.set(Calendar.MONTH, test);
cal.set(Calendar.DAY_OF_MONTH, date_pick.getDayOfMonth());
/* retriving the yyyy mm dd values here*/
set_year = cal.get(Calendar.YEAR);
set_month= cal.get(Calendar.MONTH);
set_day = cal.get(Calendar.DAY_OF_MONTH);
Log.d("kunal","datesis "+set_year+" "+set_month+" "+set_day);
string_date = set_year+"-"+set_month+"-"+set_day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
try {
d1 = sdf.parse(string_date);
Log.d("kunal","date came "+d1);
System.out.println(sdf.format(d1));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
date_txt.setText(sdf.format(d1));
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");
}