Android countdown from one date to another - android

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

Related

Android: Show elapsed time on UI for given start time and continue to update it with handler (timer)

I get a project start time from a web service and work out the time the project had taken up to the current date. I store the datetime I get from the web in the startTimeList.
Here is how I'm getting the current elapsed time on the project:
public void setTimeElapsed() {
try {
Calendar calStart = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
calStart.setTime(sdf.parse(startTimeList.get(0)));
long startMillis = calStart.getTimeInMillis();
long now = System.currentTimeMillis();
long difference = now - startMillis;
Calendar calDiff = Calendar.getInstance();
calDiff.setTimeInMillis(difference);
int eYear = calDiff.get(Calendar.YEAR);
int eMonth = calDiff.get(Calendar.MONTH);
int eDay = calDiff.get(Calendar.DAY_OF_MONTH);
int eHour = calDiff.get(Calendar.HOUR_OF_DAY);
int eMin = calDiff.get(Calendar.MINUTE);
int eSec = calDiff.get(Calendar.SECOND);
mimDuration.setText(String.format("%d Months %d Days %d:%d:%d", eMonth, eDay, eHour, eMin, eSec));
} catch (ParseException e) {
Log.e(TAG, "Error: " + e.getMessage());
}
}
However this does not keep updating the elapsed time for the user to see the real time. I need to add a handler (timer) of some sorts to keep updating the time on the UI.
Any help would be appreciated. Thank you.
You can create a timerTask and use a timer to schedule it periodically. Inside the run method you can update the ui by either using runOnUiThread method or a handler.
So something like
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Long spentTime = System.currentTimeMillis() - startTime;
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
},0, interval);

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 Compare current date and user given date?

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();
}

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())

Find if CountDownTimer is Finished?

I was playing around with the CountDownTimer on Android and I came into sort of a dilemma. In my code, I have the following:
public class mCountDownTimer extends CountDownTimer{
protected boolean hasFinished = false;
public mCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
public void onFinish(){
hasFinished = true;
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
}
}
Basically I want to find out if my CountDownTimer has finished. But in the function I want to call it in, I have some code that goes:
public void function(){
public boolean finished = false;
if(interrupted)
countDownTimer.cancel();
if(temporaryCountHolder == false){
countDownTimer.start();
interrupted = true;
}
}
How can i tell whether or not my timer has finished? I want to implement something that says:
if(countDownTimer.hasFinished == true){
Time now = new Time(); //finds the current time
now.setToNow();
String lsNow = now.format("%m-%d-%Y %I:%M:%S");
lsNow += " just Started\n";
try {
dumpToFile("StepsChanged", lsNow);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
But if I put the statement right after
if(temporaryCountHolder == false)
statement, then the if statement with hasFinished will always evaluate to be false. How can I get it so that I can record the time if and only if the timer has finished?
As per your comments, the reason why you are getting the false value is because you are executing the statements before the timer has stopped.
You can go like below,
#Override
public void onFinish(){
hasFinished = true;
Time now = new Time(); //finds the current time
now.setToNow();
String lsNow = now.format("%m-%d-%Y %I:%M:%S");
lsNow += " just Started\n";
try {
dumpToFile("StepsChanged", lsNow);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
To simply record the time you can just move those methods to the onFinish method of countdowntimer class. I don't know about dumpToFile if it is a method of another class you can make it a static method and use it or even some suitable alternative methods. Hope this helps.
you need to cancel CountDownTimer in OnFinsh
#Override
public void onFinish() {
Log.v(TAG, "On Finish");
Intent intent = new Intent(TIME_OUT);
intent.putExtra("dialog", "timeout");
sendBroadcast(intent);
countDownTimer.cancel();
}

Categories

Resources