Search code examples
androidtimepickerandroid-calendarandroid-datepicker

Difference between user input year,month,day,hour,min and system year,month,day,hour,min


i have taken the user input for time and date as:

DatePicker dp = (DatePicker) findViewById(R.id.datePicker);
TimePicker tp = (TimePicker) findViewById(R.id.timePicker);

int year = dp.getYear();
int month = dp.getMonth();
int date = dp.getDayOfMonth();
int hour = tp.getCurrentHour();
int min = tp.getCurrentMinute();

and the system's current date and time as:

Calendar cal = Calendar.getInstance();

int Syear = cal.get(Calendar.YEAR);
int Smonth = cal.get(Calendar.MONTH);
int Sdate = cal.get(Calendar.DAY_OF_MONTH);
int Shour = cal.get(Calendar.HOUR_OF_DAY);
int Smin = cal.get(Calendar.MINUTE);

assume that, user will not set the date and time in past from system's current date and time. now i need the difference between user input and system's current date,time in minute or second or millisecond. how can i do that? any example, tutorial or anything will be helpful. thank you.


Solution

  • To get the difference in milliseconds, you could do something like this:

         Calendar a = Calendar.getInstance();
         Calendar now = Calendar.getInstance();
         a.set(year, month, day, hour, min);
         long difference = a.getTimeInMillis()-now.getTimeInMillis();