Compare dates in Android App - android

I am quite new to Android development, but the person has written the code is away and i have taken over this job.
There is one thing I would like to find out quickly...(--
The app is picking up the user input of a date (using a date picker) and i need add a validation to check the if the date is valid. The valid dates are 30 days from today.
After searching on the internet for long time, i've found a code i might can use:
Date today = new Date();
Date predefined = new SimpleDateFormat("yyyy-MM-dd").parse(today);
if(today.before(predefined)) {
...
}
But I am not sure how to add 30 days?
If you could tell me, that would be much appreciated.
Thanks in advance.
Edit Here is the Source code I've tried.
Calendar today = Calendar.getInstance();
today.add(Calendar.DAY_OF_MONTH,30);
if(calStartDate.compareTo(today)<0) {
Toast.makeText(GetClient.this,"It's before valid date!",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(GetClient.this,"It's a valid date!",Toast.LENGTH_SHORT).show();
}

You want the Calendar class. You can create one and set it to current time/date, and create another and set roll it forward 30 days. Then call compareTo() on one passing in the other.

Implement this logic in ur OnDateSetListener:::
class DateListner implements OnDateSetListener
{
#Override
public void onDateSet ( DatePicker view , int year , int monthOfYear ,
int dayOfMonth )
{
Date inputDate = new Date(year, monthOfYear, dayOfMonth);
Long inputTime = inputDate.getTime();
Calendar calendar=Calendar.getInstance();
Date validDate = new Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), (calendar.get(Calendar.DAY_OF_MONTH)+30));
Long validTime = validDate.getTime();
if(validTime>inputTime){
Log.e("result", "valid");
}
else
Log.e("result", "invalid");
}
}
Cheers......!!!!

Related

Android TimePicker not returning user set time but realtime, convert to long

I have a custom dialog with a datepicker and a time picker in it. The user sets the Date which all works fine. The date picker is the hidden and the time picker is shown. I am currently setting the time on the timepicker manually to 8 am.
I now want to convert the user set time in the time picker to a long which I am able to do however its showing me the current time on the phone in the logcat and not the actual set time... Thanks!
button_continue.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (timeset == false) {
Calendar calendar = Calendar.getInstance();
calendar.set(datePickerDiet.getYear(), datePickerDiet.getMonth(), datePickerDiet.getDayOfMonth());
long startTime = calendar.getTimeInMillis();
System.out.println(startTime);
// save to shared pref
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_START_DIET_DAY, startTime);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(startTime));
System.out.println(dateString);
datePickerDiet.setVisibility(View.GONE);
time_breakfast.setVisibility(View.VISIBLE);
dialog_txt.setText("At what time do you have breakfast?");
time_breakfast.setCurrentHour(8);
time_breakfast.setCurrentMinute(0);
time_breakfast.clearFocus();
timeset = true;
}
else if (timeset == true) {
// time_breakfast.setVisibility(View.VISIBLE);
Calendar calendar2 = Calendar.getInstance();
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
long breakfasttime = calendar2.getTimeInMillis();
System.out.println(breakfasttime);
SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm");
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
// startdietdialog.cancel();
ProfilePrerences.getInstance().setLongValue(DietActivity.this, ProfilePrerences.KEY_BREAKFAST_TIME, breakfasttime);
timeset = false;
}
}
});
This line is causing you the problem:
calendar2.set(time_breakfast.getCurrentHour(), time_breakfast.getCurrentMinute(), 0);
This is setting the year, month, day on calendar2 - not the hour, minute, second you intended.
Probably the easiest solution is call the direct methods - setHour, setMinute, etc., on calendar2.
Two things: you're printing the current date (new Date):
String dateString2 = formatter2.format(new Date(breakfasttime));
System.out.println(dateString2);
You have to print calendar2 time:
String dateString2 = formatter2.format(calendar2.getTime());
System.out.println(dateString2);
The other is, Greg Ennis said, you're setting calendar2 time incorrectly: there is not such method to set only the hour, minutes and seconds. You should set year, month and day also or call set(Calendar.HOUR, h), set(Calendar.MINUTE, m), etc separately

In Android, how to create a Time value?

In my Android app, I'm using the Time class. I understand getting the current time like this:
Time now = new Time();
now.setToNow();
but what I'm stumbling on is how to create a set value of 8pm in the Time class. It's not just: Time time8 = "2200";, because that's a String, and Time time8 = 2200; is an integer. So I'm stumped.
There are multiple ways to that, I think the most easiest for you would be to just set it directly:
set(int second, int minute, int hour, int monthDay, int month, int year)
Calendar rightNow = Calendar.getInstance();
int day = rightNow.get(Calendar.DAY_OF_MONTH);
int month = rightNow.get(Calendar.MONTH);
int year = rightNow.get(Calendar.YEAR);
Time time8 = new Time();
time8.set(0,0,22,day,month,year);
But i would only do it like that if you really want to use Time otherwise Calendar is much more useful
Calendar calendar8= Calendar.getInstance();
calendar8.set(Calendar.SECOND, 0);
calendar8.set(Calendar.MINUTE, 0);
calendar8.set(Calendar.HOUR_OF_DAY,22);
Could use the calendar class
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,5);
cal.set(Calendar.MINUTE,50);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date d = cal.getTime();
From android Dev.
A specific moment in time, with millisecond precision. Values typically come from currentTimeMillis(), and are always UTC, regardless of the system's time zone. This is often called "Unix time" or "epoch time".
You can do Date instead of time
Date newdate = new Date();
You can use calendar to break it down to what you actually need.

Calculate with date in Android

Does anyone here know what the best way is to calculate the date 2 days in the past?
I've got this piece of code to retrieve the current date:
public static String getDateTime (String Format){
SimpleDateFormat sdf = new SimpleDateFormat(Format);
return sdf.format(new Date());
}
But I want to be able to calculate the date 2 days in the past. So decrease the date with 2 days. Anyone who knows what the best way is to do this?
Thanks in advance
Using Calendar is probably the easiest way. Assuming that you have defined Format as per the question:
// get Now
Calendar cal = Calendar.getInstance();
// go back two days
cal.add(Calendar.DAY_OF_YEAR, -2);
// display
SimpleDateFormat sdf = new SimpleDateFormat(Format);
String string = sdf.format(cal.getTime());
Just use Calendar's add() function:
Calendar c = Calendar.getInstance();
c.setTime(yourDateObject);
c.add(Calendar.DAY_OF_MONTH, -2);
It will automatically change the month, year, etc. if necessary.

Android issue displaying day of week string

I have seen many examples of working with dates in Android using Calendar and GregorianCalendar classes.
Recently I came across the following in Android Developers Time documentation:
The Time class is a faster replacement for the java.util.Calendar and java.util.GregorianCalendar classes. An instance of the Time class represents a moment in time, specified with second precision.
This prompted me to replace all the Calendar functions with the faster Time class functions.
Here is my code for reading the date stored in the SQLite database:
// extract milliseconds (long) value from SQLite database
Long timeLong = note.getLong(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATE));
Time currentTime.set(timeLong);
Here is the partial code for preparing the integer values for populating the date picker and displaying the formatted date string in the mPickDate button:
mDay = currentTime.monthDay; // Day of the month (0-31)
mMonth = currentTime.month; // Month (0-11)
mYear = currentTime.year; // Year
mPickDate.setText(currentTime.format("%A, %d %b %Y")); // using strftime equivalent to dateFormat = new SimpleDateFormat("E, dd MMM yyyy");
Note the format %A used to get the long string for the day of the week.
This part of the formatting code works perfectly well and displays the correct string with the formatted date, including the correct day of the week.
Clicking on the mPickDate button invokes the DatePicker widget, which allows for changing and setting the new date.
The following code shows the handling of the newly selected date from the DatePicker:
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// new method using Time class
currentTime.set(dayOfMonth, monthOfYear, year);
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
// old method using GregorianCalendar class
//mCalendar = new GregorianCalendar(year, monthOfYear, dayOfMonth);
//mPickDate.setText(dateFormat.format(mCalendar.getTime()));
}
};
The mPickDate button gets the correct date string displayed, as selected in the Date Picker, except for the day of the week (%A), which is always shown as Sunday. Why ?
Note that mPickDate.SetText code is identical to the one used earlier to format the button date string, extracted from the SQLite database field.
I had to modify the above code, by adding an extra line of code to set the date value in the currentTime Time object once again:
currentTime.set(dayOfMonth, monthOfYear, year);
currentTime.set(currentTime.toMillis(true));
mPickDate.setText(currentTime.format("%A, %d %b %Y"));
My question is: why it was necessary to use the currentTime.set procedure twice in the above DatePickerDialog.OnDateSetListener code, in order to get the day of the week string to display correctly ?
Would this possibly be an issue with Android Timecode itself (using SDK version 16) ?

Date getMonth() in java from 0-11 messes up searches in database?

Second EDIT:
Looks like my issue might be where the date is set from the date picker dialog:
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear + 1;
mDay = dayOfMonth;
updateDisplay();
}
}
I am +1 to the month, but never taking that off again when i compare for the database...
EDIT:
Okay I did double checked this (finally got to it). Sure enough the
Date test1 = new Date(cobj.getTime().getTime()); //from the Calendar passed in
So the date retrieved from the database is the right date. The one that comes back from my dialog even though it displays correctly using:
String val = cobjstrong text.get(Calendar.MONTH) + "/" +
cobj.get(Calendar.DAY_OF_MONTH) + "/"+ cobj.get(Calendar.YEAR);
...is actually a month ahead when I look at the object as cobj.getTime().getTime(); (a long for the dates I use). Is there some other method or conversion I am missing?
Should I not be using the .getTime on the Calendar Object just to get a long from that (with a call to getTime again on the Date object?). Sometimes it seems to me that my best bet is to store longs in milliseconds to the database and then just retrieve them and do the Date conversions there?
PRE-EDIT question:
SO I have this Date field in a database, that I can store a date to and read a date from, when I read em... I have to add a +1 to the .getMonth() because date returns that as a number 0-11, instead of 1-12. After dealing with this issue and a few others (like .getMinutes returning an int, so if the time is 5:00 only 5:0 is displayed?)but I finally got the date displaying just great, but I found out when I try to query the database on a date things are off I am guessing by one month. So that means a month of
9/8/2011
(dd/mm/YYYY) format, will not query right when using the following ORMLite query:(Notice the .qe, GreaterThanEqual in ormlite).
public void updateDatePickerButtonUI(Calendar cobj, int widget) {
String val = cobj.get(Calendar.MONTH) + "/"+ cobj.get(Calendar.DAY_OF_MONTH)
+ "/"+ cobj.get(Calendar.YEAR);
btnChooseDateReview.setText(val);
//the following just won't query correctly, its a month off
try {
//sessionDate
QueryBuilder<SessionsData, Integer> sb =
mDB.getSessionsDao().queryBuilder();
sb.where().ge(SessionsData.SESSIONSDATE_ID_NAME, cobj.getTime());
List<SessionsData> sessions = mDB.getSessionsDao().query(sb.prepare());
for (int i = 0; i < sessions.size(); i++) {
try {
mDB.getClientsDao().refresh(sessions.get(i).getClient());
mDB.getPackagesDao().refresh(sessions.get(i).getPackage());
} catch (SQLException e) {
...
}
}
theSessions = new CustomSessionReviewAdapter(mContext,
R.layout.session_review_row, sessions);
theSessions.notifyDataSetChanged();
theList.setAdapter(theSessions);
} catch (SQLException e) {
...
}
}
So I must be handling dates wrong, maybe adding to the month for display purposes is not right? or something... maybe in my query with the Calendar object, I can make that month part 0-11 or something...not sure what avenue to take here.
I'm a little confused #CodeJoy. I don't see any references to +1 in your code. I assume that you are doing a +1 while you are building the val for your button text?
ORMLite stores the Date field as a string via the Sqlite driver (i.e. something like 2011-08-10 18:33:30.316) and I am wondering if the conversion to/from a Calendar object generates a Date that does not match the database exactly. Maybe the milliseconds have been truncated? Are you creating a Calendar from the button date string?
Most likely your problem has nothing to do with the +/- 1 issue around the month. The getTime() method should do that conversion appropriately.
I would debug your app and see what the cobj.getTime() returns for a date and then do a mDB.getSessionsDao().queryForAll() and take a look at how the Date is being returned from the database driver.

Categories

Resources