How to Compare current date and user given date? - android

I want to compare the current date and the date that set by user in my "cal_set" calendar, i want to accept the date if date is today date or upcoming date else show toast if date is passed.
This is my onDateSet method.
public void onDateSet(DatePicker arg0, int year, int month, int day)
{
// TODO Auto-generated method stub
cal_set.set(Calendar.DAY_OF_MONTH,day);
cal_set.set(Calendar.MONTH, month);
cal_set.set(Calendar.YEAR, year);
if(cal_set.getTime().after(cal_now.getTime))
{
tv_date.setText(new StringBuffer().append(day).append("/").append(month).append("/").append(year));
}
else
{
Toast.makeText(getApplicationContext(),"Please select upcoming date", Toast.LENGTH_LONG).show();
}
}
};
i am setting date in cal_now when user click on view that calles onDateSet method.
iv_date.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
day_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.DAY_OF_MONTH);
month_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.MONTH);
year_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.YEAR);
cal_now = Calendar.getInstance();
showDialog(ID_DATE);
}
});
protected Dialog onCreateDialog(int id)
{
// TODO Auto-generated method stub
switch (id)
{
case ID_DATE:
return new DatePickerDialog(this, onDateSetListener, year_now, month_now, day_now);
default:
break;
}
return null;
}
any help please.

you can compare Date with compareTo(). However, in your case, you can use Calendar methods setMaxDate() and setMinDate().

You can simply use "now = new Date();" to get the actual date.
Then to test if the entered date is superior or equal to the actual date, use:
if (setdate.compareTo(now)>=0) {
// do your stuff here.
}

public static boolean CompareDates(String strDate1,String strDate2)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(strDate1);
Date date2 = sdf.parse(strDate2);
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)==0)
{
return true;
}else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}

I solved my problem finally, now i let the datepicker get date from user and than i set that date in EditText, when user clicks on submit button i just get strings from edittext and parse them into date format like this:
s_date_temp = date_format.parse(et_sdate.getText().toString());
e_date_temp = date_format.parse(et_edate.getText().toString());
After that i compare these dates like this:
if(s_date_temp.after(e_date_temp))
{
Toast toast = Toast.makeText(getApplicationContext(), "Error: The Start Date Must Occur Prior To Th End Date!", Toast.LENGTH_LONG);
toast.show();
}

Related

Compare two time continously in android

I want to run Async Task in Android every intervals.
my interval is = { 15 min , 30 min , 1 hour ....etc
Depending on the users' choice.
When I start my application then I want to fetch my current time and after every n interval I want to execute Async Task
int intv = 15;
SimpleDateFormat sd = new SimpleDateFormat(
"HH:mm:ss");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println(sd.format(date));
String currenttime = sd.format(date);
Date myDateTime = null;
try
{
myDateTime = sd.parse(currenttime);
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println("This is the Actual Date:"+sd.format(myDateTime));
Calendar cal = new GregorianCalendar();
cal.setTime(myDateTime);
cal.add(Calendar.MINUTE , intv ); //here I am adding Interval
System.out.println("This is Hours Added Date:"+sd.format(cal.getTime()));
try {
Date afterintv = sd.parse(sd.format(cal.getTime()));
if(afterintv.after(myDateTime)){ //here i am comparing
System.out.println("true..........");
new SendingTask().execute; //this is the function i have to execute
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am not getting how to do.
If you want to run the AsyncTask after sometime you can use Thread.sleep in your AsyncTask. In this case is the SendingTask class. Here is a sample:
class SendingTask extends AsyncTask{
// Interval is in milliseconds
int interval = 1000;
public SendingTask(int interval) {
// Setting delay before anything is executed
this.interval = interval;
}
#Override
protected Object doInBackground(Object[] params) {
// Wait according to interval
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// update UI and restart asynctask
textView3.setText("true..........");
new SendingTask(3000).execute();
}
}

How to run a function just one time

I need to run a function only once (when it's night, change the image of the imageview) and when I use it in oncreate(), it runs every time I start the
activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAnim();
}
}
private void startAnim(){
Date dateNow=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String night=String.format("%tF",dateNow)+" 19:00:00";
try {
Date dateNight=sdf.parse(night);
if(dateNow.after(dateNight)){
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
RotateAnimation ra=new RotateAnimation(0,100,width/2,height/2-80);
ra.setDuration(4000);
sunMoon.startAnimation(ra);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Either a file or store in a Shared Preference. Example for a save method:
private void saveLastRanTime(String key, long lastRunTime) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(key, lastRunTime); // Store the key somewhere instead of passing in each time
editor.apply();
}
Example check:
private boolean wasLastRunToday(String keyOfPreference) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
long lastRanAt = prefs.getLong(keyOfPreference, -1); // Save key somewhere..
if (lastRanAt == -1) { // In the event it was never saved before.
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(lastRanAt);
int dayLastRanAt = cal.get(Calendar.DAY_OF_YEAR);
cal.setTimeInMillis(System.currentTimeMillis());
int today = cal.get(Calendar.DAY_OF_YEAR);
return today == dayLastRanAt;
}
Which would make your startAnim() method look more like:
private void startAnim() {
if (wasLastRunToday("LAST_ANIMIATION_RUNTIME")) {
return;
}
Date dateNow=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String night=String.format("%tF",dateNow)+" 19:00:00";
try {
Date dateNight=sdf.parse(night);
if(dateNow.after(dateNight)) {
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
RotateAnimation ra=new RotateAnimation(0,100,width/2,height/2-80);
ra.setDuration(4000);
sunMoon.startAnimation(ra);
saveLastRanTime("LAST_ANIMIATION_RUNTIME", dateNow.getTime());
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Record the time of your last time running startAnim() in a file. Read this file when you start the activity to decide run startAnim() or not.

Datepicker dialog picks wrong year

I am trying to get Date from Datepicker, my code is below
dpResult = (DatePicker) findViewById(R.id.dpResult);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Calendar current = Calendar.getInstance();
gettingDate();
}
private void gettingDate() {
// TODO Auto-generated method stub
int day = dpResult.getDayOfMonth();
int month= dpResult.getMonth();
int year = dpResult.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
formatedDate = sdf.format(new Date(year, month, day));
// You can parse the String back to Date object by calling
try {
date = sdf.parse(formatedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), ""+formatedDate, 1000).show();
}
});
my toast shows date-month correctly but in year first two digits as 39 i.e like 3913,3914 etc please help me
you have to use this format for getting perfect and right year.
dpResult.getYear()-1900;
use dpResult.getYear()-1900
int year = dpResult.getYear();
Date is deprecated, you should use Calendar instead with the following syntax
Calendar cal = Calendar.getInstance()
cal.set(dpResult.getYear(), dpResult.getMonth()-1,getDayOfMonth())

Android countdown from one date to another

I'm trying to countdown from a start date to an end date. For example, on 12 October 2012 to 14 October 2012.
I would like to get the current date and from this date do the countdown to the next.
Do you have any good examples?
This might prove too inflexible a solution but you could try converting the dates to long values, subtracting one from the other, and then using the android countdown timer class to do your countdown.
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date a = null, b = null;
try {
a = sdf.parse("14-10-2012");
b = sdf.parse("12-10-2012");
} catch (ParseException e) {
e.printStackTrace();
}
// .getTime() does the conversion: Date --> long
CountDownTimer cdt = new CountDownTimer(a.getTime() - b.getTime(), 1000) {
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
public void onFinish() {
// TODO Auto-generated method stub
}
}.start();
more information about the class can be found here:
http://developer.android.com/reference/android/os/CountDownTimer.html

Time Picker Android

How to set previous selected value in TimePicker?
I mean, click on TextView, TimePicker dialog occurs, then I select the time and set it in the TextView, e.g. 12:30 PM on TextView.
After that, if I want to change the time, click again to TextView and then TimePicker dialog should show the previous selected value. So the TimePicker should display 12:30 PM.
How can I do that?
If you create Time Picker Dialog with onCreateDialog and call it it will automatically store the previous value.
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
TimePickerDialog timeDlg = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// TODO Auto-generated method stub
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
time = " PM";
} else if (hourOfDay < 12 && hourOfDay != 0) {
time = " AM";
} else if (hourOfDay == 12) {
time = " PM";
} else if (hourOfDay == 0) {
hourOfDay = 12;
time = " AM";
}
Toast.makeText(
getApplicationContext(),
new StringBuilder().append(pad(hourOfDay))
.append(":").append(pad(minute))
.append(time), Toast.LENGTH_SHORT)
.show();
}
}, 12, 00, false);
timeDlg.setMessage("Set Time:");
timeDlg.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Dismiss",
Toast.LENGTH_SHORT).show();
}
});
return timeDlg;
}
return null;
}
Use showDialog(id); to Show the Dialog.

Categories

Resources