1

I want to use the calendarDaysBetween() below method in my TextView, or I want my TextView to display difference of two dates. Can anyone help me with this?

public class MainActivity extends FragmentActivity {
    static EditText metTodate, metFromdate, metInTime, metOutTime;
    static long no_of_days1;
    static long no_of_days2;
    Button mbtnApplyLeave;
    ImageView mivBack;
    RadioButton halfday1, halfday2, first_half, second_half, first_half1, second_half1, full_day1, full_day2;
    static TextView no_of_days;
    static TextView no_of_days3;
    public static String str;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        metTodate = (EditText)findViewById(R.id.etTodate);
        metFromdate = (EditText)findViewById(R.id.etFromdate);
        metInTime = (EditText)findViewById(R.id.etInTime);
        metOutTime = (EditText)findViewById(R.id.etOutTime);
        mivBack = (ImageView)findViewById(R.id.ivBack);
        halfday1 = (RadioButton)findViewById(R.id.halfday1);
        halfday2 = (RadioButton)findViewById(R.id.halfday2);
        first_half = (RadioButton)findViewById(R.id.firsthalf1);
        second_half = (RadioButton)findViewById(R.id.secondhalf1);
        first_half1 = (RadioButton)findViewById(R.id.firsthalf2);
        second_half1 = (RadioButton)findViewById(R.id.secondhalf2);
        full_day1 = (RadioButton)findViewById(R.id.fullday1);
        full_day2 = (RadioButton)findViewById(R.id.fullday2);
        no_of_days = (TextView)findViewById(R.id.etnoofdays);


        // Here is my method where I want my text view to display dates.
        no_of_days.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
            }
        });
    }

    // Both date picker dialogs
    public void showTruitonDatePickerDialog(View v) {
        DialogFragment newFragment = new DatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);
            // Create a new instance of DatePickerDialog and return it

            return new DatePickerDialog(getActivity(), this, year, month, day);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            metTodate.setText(day + "/" + (month + 1) + "/" + year);
        }
    }

    public void showFromDatePickerDialog(View v) {
        DialogFragment newFragment = new FromDatePickerFragment();
        newFragment.show(getSupportFragmentManager(), "datePicker");
    }

    public static class FromDatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            // Use the current date as the default date in the picker
            final Calendar c1 = Calendar.getInstance();
            int year = c1.get(Calendar.YEAR);
            int month = c1.get(Calendar.MONTH);
            int day1 = c1.get(Calendar.DAY_OF_MONTH);

            // Create a new instance of DatePickerDialog and return it
            return new DatePickerDialog(getActivity(), this, year, month, day1);
            // calendarDaysBetween(Calendar metFromdate, Calendar metTodate);
        }

        public void onDateSet(DatePicker view, int year, int month, int day) {
            // Do something with the date chosen by the user
            metFromdate.setText(day + "/" + (month + 1) + "/" + year);
        }
    }

    public static long calendarDaysBetween(Calendar metFromdate, Calendar metTodate) {
        // Create copies so we don't update the original calendars.

        Calendar start = Calendar.getInstance();
        start.setTimeZone(metFromdate.getTimeZone());
        start.setTimeInMillis(metFromdate.getTimeInMillis());

        Calendar end = Calendar.getInstance();
        end.setTimeZone(metTodate.getTimeZone());
        end.setTimeInMillis(metTodate.getTimeInMillis());

        // Set the copies to be at midnight, but keep the day information.

        start.set(Calendar.HOUR_OF_DAY, 0);
        start.set(Calendar.MINUTE, 0);
        start.set(Calendar.SECOND, 0);
        start.set(Calendar.MILLISECOND, 0);

        end.set(Calendar.HOUR_OF_DAY, 0);
        end.set(Calendar.MINUTE, 0);
        end.set(Calendar.SECOND, 0);
        end.set(Calendar.MILLISECOND, 0);

        // At this point, each calendar is set to midnight on
        // their respective days. Now use TimeUnit.MILLISECONDS to
        // compute the number of full days between the two of them.
        no_of_days1 = TimeUnit.MILLISECONDS.toDays(Math.abs(end.getTimeInMillis() - start.getTimeInMillis()));

        String finalresult = new Double(no_of_days1).toString();
        no_of_days.setText(finalresult);

        return no_of_days1;
    }
}
Will
  • 24,082
  • 14
  • 97
  • 108
Ankit Gupta
  • 64
  • 10
  • try joda time http://stackoverflow.com/questions/3802893/number-of-days-between-two-dates-in-joda-time. for android https://github.com/dlew/joda-time-android – Raghunandan Dec 29 '15 at 07:04

4 Answers4

1

try this

SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date past = format.parse("05/06/2015");
Date now = new Date();

System.out.println(TimeUnit.MILLISECONDS.toMinutes(now.getTime() - past.getTime()) + " minutes ago");
System.out.println(TimeUnit.MILLISECONDS.toHours(now.getTime() - past.getTime()) + " hours ago");
System.out.println(TimeUnit.MILLISECONDS.toDays(now.getTime() - past.getTime()) + " days ago");

It will give you difference in minute and hours also from current date, you can use your own date format and own date objects

Ravi
  • 34,851
  • 21
  • 122
  • 183
  • i have created a two date picker dialog method for different dates .But the problem is that i am not able to use each other instance or method in another.and if i want to use third method in the which i have calculated diff. of dates .i am not able to use it in a textview click of no_of_days – Ankit Gupta Dec 29 '15 at 07:14
1

You can use the following code to get a date difference in number of days.

public void calendarDaysBetween(Calendar metFromdate, Calendar etTodate)
{
long diff = (metFromdate.getTimeInMillis() - metTodate.getTimeInMillis());
long no_of_days1 = Math.abs(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
 no_of_days.setText(no_of_days1+"");
}

First declear Calendar object

public Calendar metFromdate= Calendar.getInstance();
public Calendar metTodate== Calendar.getInstance();

Change first DatePicker values

public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
       metFromdate.set(Calendar.YEAR, year);
    metFromdate.set(Calendar.MONTH, month);
    metFromdate.set(Calendar.DAY_OF_MONTH, day);
    }

change second DatePicker values

public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        metTodate.set(Calendar.YEAR, year);
    metTodate.set(Calendar.MONTH, month);
    metTodate.set(Calendar.DAY_OF_MONTH, day);
    }

change button click

 no_of_days.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            calendarDaysBetween(metFromdate, metTodate);
        }
    });
Akash Jagtap
  • 404
  • 2
  • 8
0

you used it

   Calendar date1 = Calendar.getInstance(); Calendar date2 =
   Calendar.getInstance();

   date1.clear();
   date1.set(datePicker1.getYear(),datePicker1.getMonth(),datePicker1.getDayOfMonth());
   date2.clear();
   date2.set(datePicker2.getYear(),datePicker2.getMonth(),datePicker2.getDayOfMonth());

   long diff = date2.getTimeInMillis() - date1.getTimeInMillis();

   float dayCount = (float) diff / (24 * 60 * 60 * 1000);

   textView.setText(Long.toString(diff) + " " + (int) dayCount);
  • can you brief me what is datepicker in my case??.i m new to programming thats why i m not able to get what is date picker in that case – Ankit Gupta Dec 29 '15 at 09:12
0
dependencies {
     compile fileTree(dir: 'libs', include: ['*.jar'])
     testCompile 'junit:junit:4.12'
     ........
     ........
     compile 'joda-time:joda-time:2.2'
}

and

public String getTimeAgo(long ago){

    DateTime timeAgo = new DateTime(ago*1000L);
    DateTime now = new DateTime();
    Period period = new Period(timeAgo, now);

    PeriodFormatter formatter = new PeriodFormatterBuilder()
            .appendYears().appendSuffix(" Years, ")
            .appendMonths().appendSuffix(" Months, ")
            .appendWeeks().appendSuffix(" Weeks, ")
            .appendDays().appendSuffix(" Days, ")
            .appendHours().appendSuffix(" Hours, ")
            .appendMinutes().appendSuffix(" Minutes, ")
            .appendSeconds().appendSuffix(" Seconds ago ")
            .printZeroNever()
            .toFormatter();

    String elapsed = formatter.print(period);

    return elapsed;
}

and

 yourTextView.setText(getTimeAgo(long-your_past_date_millis));
Milos Lulic
  • 627
  • 5
  • 22