How to query with comparison for current date in Parse - android

I am doing Parse + Android app. As parse automatically creates createdAt field of type Date for each object I want to construct a query where I compare current date.
This is something that I want to do:
ParseQuery<ParseObject> mealPlan = ParseQuery.getQuery("MealPlans");
mealPlan.whereEqualTo("created_at", current Date );
So basically I want to retrieve objects that were created today.

With whereEqualTo(), you're just querying objects created at exactly current Date. You should query the range of dates >= the 12:00am of today and < 12:00am of tomorrow (or <= 11:59pm of today if you want).
Use Parse's whereLessThan() and whereGreaterThanOrEqualTo().
// First, get the two dates (start and end of day)
// You'll find many algorithms to calculate these,
// but here's a quick and easy one:
Calendar cal = new GregorianCalendar();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// start of today
Date today = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, 1); // add one day to get start of tomorrow
// start of tomorrow
Date tomorrow = cal.getTime();
// Your query:
ParseQuery<ParseObject> mealPlan = ParseQuery.getQuery("MealPlans");
mealPlan.whereGreaterThanOrEqualTo("createdAt", today);
mealPlan.whereLessThan("createdAt", tomorrow);
NOTE:
The date calculation shown above is just a simple one, as the original question here is for the query and not calculating date. You will find many algorithms and libraries such as Joda-Time, which take into account the edge cases and daylight saving cases as well.

Related

Add one day to calendar to make test if-else

I use DateTime values in my app. I can create Lessons, and I have to set the beginning nd the end of that lesson.
Let's say I create like this :
English - Beginning 07.05.2017 End 07.07.2017
Then I want to modify the end of that lesson and put :
07.06.2017
I check to see if the dates are OK, but I'm not sure about what I did, because I dont want to let the user to modifiy or create lessons in the past, but if he creates a lesson that finishes the current day, that's ok.
I wrote like this in my if else :
String date1 = datedebut.getText().toString();
String date2 = datefin.getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date_debutnew = dateFormat.parse(date_initial);
Date date_derniernew = dateFormat.parse(date_derniercours);
Calendar calendar = Calendar.getInstance();
if (date_debutnew.after(date_derniernew) || date_derniernew.before(calendar.getTime()))
{ ... }
How can I add one day to that calendar ?
Thank you for the future hlep.
You can use compareTo() method of Date.
It will return,
a value 0 if the argument Date is equal to this Date;
a value less than 0 if this Date is before the Date argument;
a value greater than 0 if this Date is after the Date argument.
From what I understand of the problem, your new Finish date should be after the new Start date and before the designated end Date.
so, the condition should be :
if (date_derniernew.after(date_debutnew) || date_derniernew.before(date2)) {
..}

Taking date and time Strings from a SQLite database and setting AlarmManager

So, I have been trying this for a long time. I need to save the date and time as a String (DD-MM-YYYY & HH:mm) in a SQLite database.
Now I have to set up my AlarmManager to show notifications, but AlarmManager takes the time and date in milliseconds.
How can I convert these into milliseconds?
What is the right way to store Date and Time in a SQLite DB?
Which is the right way to store Date and Time in sqlite ?
You might find it easier in the end to store your dates as milliseconds in your SQLite database (using SQLite's INTEGER data type). This makes it very easy to use that value for creating Calendar objects or for using it in creating an AlarmManager alarm. But if you store the date in a String format in your database, you will probably find yourself performing String manipulation on it.
If you store your date as milliseconds in your database, it is very easy to create a Calendar object from it and extract the year, month and day:
// get millis from database
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
For storing times, I find it best to store them as a 24-hour string in the "HH:MM" format. Android's TimePickers accept and return hours in 24-hour format, so this just makes life easier.
You still need to do some minimal String manipulation to get the int hours and minutes from "HH:MM", but it can be as simple as:
String timeString = "18:30";
int hours = Integer.valueOf(timeString.split(":")[0]);
int minutes = Integer.valueOf(timeString.split(":")[1]);
But if you wanted to, you could even store your times in millis as a SQLite INTEGER, then use that value to create a new Calendar object and extract the hours and minutes from it:
// get millis from database
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTES);
You can use SimpleDateFormat to do this:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String time = "12-01-2014 10:23";
long millis = format.parse(time).getTime();
This should work. I have something like this too, and I set an extra column where I save the milliseconds from this date inside the database, so I can get it directly.

Android converting calendar in one TimeZone to local TimeZone

I am using following code to convert timezone (GMT-3) to device local timezone.
int hour=17,minute=0,day=12,month=6,year=2014;
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"));
cal.set(year, (month-1), day,hour,minute);
cal.setTimeZone(TimeZone.getDefault());
Log.d("Time", cal.get(Calendar.DATE)+"/"+cal.get(Calendar.MONTH)+"/"+cal.get(Calendar.YEAR)+" , "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+" "+cal.get(Calendar.AM_PM));
My local timezone is GMT+5:30
Expected result is
Time 13/5/2014, 1:30 0
But I am getting the result
12/5/2014 , 13:30 1
Sorry for you, GregorianCalendar is sometimes the hell. Your problem is following:
If you immediately set the timezone after having set the fields for year, month etc. then this mutable calendar class will only shift the timezone retaining the already set fields containing the local time. Those fields for year, month etc. will NOT be recalculated. This behaviour causes a shift on the global timeline represented by cal.getTime(), too.
In order to force the calendar object to recalculate the fields you need to call a getter. Watch out for following code and especially remove the comment marks to see the effect.
int hour = 17, minute = 0, day = 12, month = 6, year = 2014;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mmZ");
TimeZone tz1 = TimeZone.getTimeZone("GMT-3");
sdf.setTimeZone(tz1);
Calendar cal = new GregorianCalendar(tz1);
cal.set(year, (month - 1), day, hour, minute);
// System.out.println(sdf.format(cal.getTime()));
// System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
TimeZone tz2 = TimeZone.getTimeZone("GMT+0530");
sdf.setTimeZone(tz2);
cal.setTimeZone(tz2);
System.out.println(sdf.format(cal.getTime()));
System.out.println("Hour=" + cal.get(Calendar.HOUR_OF_DAY));
Output with comment-disabled lines:
2014-06-12T17:00+0530
Hour=17
Output with enabled lines after having removed the comment marks:
2014-06-12T17:00-0300
Hour=17
2014-06-13T01:30+0530
Hour=1

How to add holidays in Android Calendar?

I am trying to add a list of holidays to my calendar. I am using the Caldroid library for displaying the calendar. I want to display a list of holidays in every month for which I need to select specific dates in every month. How do I do that ? The following is what I have tried:
CODE :
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -18);
Date blueDate = cal.getTime();
cal = Calendar.getInstance();
cal.add(Calendar.DATE, 16);
int diff = cal.get(Calendar.JANUARY);
cal.add(diff, 10);
Date greenDate = cal.getTime();
I believed that diff would set the month to January and highlight the 11th of January cause I have given the value as 10 but it doesn't do so and I believe it is because I have instantiated the cal to getInstance() which would return the current month.
UPDATE :
Thanks to Meno, I have achieved the following but when I set the calendar to the second time, it takes only the updates value and does not set the first date (very obvious) but I want to know how to set multiple dates in a month without re-instantiating a new GregorianCalendar object for every month. Simply put, how do I set an array of dates in a month.
GregorianCalendar greg_cal = new GregorianCalendar();
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 1);
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 18);
Thanks in advance.
Your question does not appear to be clear. Nevertheless I try an answer. Instead of
cal = Calendar.getInstance(); // In Thailand this gives the buddhist calendar, do you want this?
cal.add(Calendar.DATE, 16); // 16 days from now, what is the intention or meaning???
cal.add(diff, 10); // first argument must be a defined constant in java.util.Calendar
I assume you just want to select a fixed date (as holiday). If so then you can call the set()-method and don't need to add days to move your calendar date forth and back:
GregorianCalendar cal = new GregorianCalendar(); // including currrent year
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 11);
Then you get as date the 11th of January in current year. By the way:
int diff = cal.get(Calendar.JANUARY);
This line is nonsense because:
Calendar.JANUARY is an int constant which is zero and denotes a value (the month) not a field. But the get(int)-method expects a field constant. The field constant with value zero corresponds to Calendar.ERA. Finally the line yields the era of cal, namely int diff = GregorianCalendar.AD = 1; assuming you use the gregorian calendar. This is surely not what you want???
UPDATED because of extra question in comment:
Reusing means that you don't create a new instance for the next calculation but reuse the same one (GregorianCalendar is mutable!). For example:
GregorianCalendar cal = new GregorianCalendar(); // including currrent year
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.DAY_OF_MONTH, 11);
Date holiday1 = cal.getTime();
cal.set(Calendar.MONTH, Calendar.DECEMBER); // no new instance => reuse cal
cal.set(Calendar.DAY_OF_MONTH, 24);
Date holiday2 = cal.getTime();
...
I have also written about limiting to manipulations of month and day-of-month only because with manipulation of week-related fields the state of reused Calendar-instance depends on the order of field manipulations (very ugly and surprising).
Anyway, it is always safer to use immutable types which are available in Java 8 (not useable on Android), JodaTime and my alpha-state-library. I admit that the first contact with JodaTime can cause you feeling like lost because there are so many methods (the documentation standard is good for open-source but less good than for example in JSR-310). In your use-case I would use the type org.joda.time.LocalDate as start because you really have just a plain-date-use-case. Google and SO are your friends if you want to see more documentation beyond the original Joda documentation.
UPDATE due to extended question:
You have forgotten one important thing in your new code, namely to add the results of calendar setting to a holiday list, see here the modification:
List<Date> holidays = new ArrayList<Date>();
GregorianCalendar greg_cal = new GregorianCalendar();
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 1);
holidays.add(greg_cal.getTime());
greg_cal.set(Calendar.MONTH, Calendar.JANUARY);
greg_cal.set(Calendar.DAY_OF_MONTH, 18);
holidays.add(greg_cal.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for (Date d : holidays) {
System.out.println(sdf.format(d));
}
// output:
2014-01-01
2014-01-18
In an external library like JodaTime you would just use org.joda.time.LocalDate instead.
List<LocalDate> holidays = new ArrayList<LocalDate>();
LocalDate today = LocalDate.now();
holidays.add(today.withMonthOfYear(1).withDayOfMonth(1));
holidays.add(today.withMonthOfYear(1).withDayOfMonth(18));
It is pretty simple (similar in my unfinished date-and-time-library, too).

date retreival in android

In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();
you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.
Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}

Categories

Resources