Android calculate days between two dates
Your code for generating date object:
Date date = new Date("2/3/2017"); //deprecated
You are getting 28 days as answer because according to Date(String)
constructor it is thinking day = 3,month = 2 and year = 2017
You can convert String to Date as follows:
String dateStr = "2/3/2017";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateStr);
Use above template to make your Date object. Then use below code for calculating days in between two dates. Hope this clear the thing.
It can de done as follows:
long diff = endDateValue.getTime() - startDateValue.getTime();
System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
Please check link
If you use Joda Time it is much more simple:
int days = Days.daysBetween(date1, date2).getDays();
Please check JodaTime
How to use JodaTime in Java Project
Android Days between two dates
Please refer this code, this may help you.
public String getCountOfDays(String createdDateString, String expireDateString) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
Date createdConvertedDate = null, expireCovertedDate = null, todayWithZeroTime = null;
try {
createdConvertedDate = dateFormat.parse(createdDateString);
expireCovertedDate = dateFormat.parse(expireDateString);
Date today = new Date();
todayWithZeroTime = dateFormat.parse(dateFormat.format(today));
} catch (ParseException e) {
e.printStackTrace();
}
int cYear = 0, cMonth = 0, cDay = 0;
if (createdConvertedDate.after(todayWithZeroTime)) {
Calendar cCal = Calendar.getInstance();
cCal.setTime(createdConvertedDate);
cYear = cCal.get(Calendar.YEAR);
cMonth = cCal.get(Calendar.MONTH);
cDay = cCal.get(Calendar.DAY_OF_MONTH);
} else {
Calendar cCal = Calendar.getInstance();
cCal.setTime(todayWithZeroTime);
cYear = cCal.get(Calendar.YEAR);
cMonth = cCal.get(Calendar.MONTH);
cDay = cCal.get(Calendar.DAY_OF_MONTH);
}
/*Calendar todayCal = Calendar.getInstance();
int todayYear = todayCal.get(Calendar.YEAR);
int today = todayCal.get(Calendar.MONTH);
int todayDay = todayCal.get(Calendar.DAY_OF_MONTH);
*/
Calendar eCal = Calendar.getInstance();
eCal.setTime(expireCovertedDate);
int eYear = eCal.get(Calendar.YEAR);
int eMonth = eCal.get(Calendar.MONTH);
int eDay = eCal.get(Calendar.DAY_OF_MONTH);
Calendar date1 = Calendar.getInstance();
Calendar date2 = Calendar.getInstance();
date1.clear();
date1.set(cYear, cMonth, cDay);
date2.clear();
date2.set(eYear, eMonth, eDay);
long diff = date2.getTimeInMillis() - date1.getTimeInMillis();
float dayCount = (float) diff / (24 * 60 * 60 * 1000);
return ("" + (int) dayCount + " Days");
}
How to calculate number of days between two datepicker in android and display in the edit text
public class ResourceActivity extends AppCompatActivity {
EditText date,dateto,days;
DatePickerDialog datePickerDialog;
Button save_btn;
Calendar c1,c2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_resource);
date = findViewById (R.id.date);
dateto = findViewById (R.id.dateto);
days = findViewById (R.id.days);
save_btn = findViewById (R.id.save_btn);
save_btn.setOnClickListener (new View.OnClickListener ( ) {
@Override
public void onClick(View view) {
// loadsave();
try {
String d1 = date.getText ().toString ();
String d2 = dateto.getText ().toString ();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date date1 = simpleDateFormat.parse(d1);
Date date2 = simpleDateFormat.parse(d2);
long difference = Math.abs(date1.getTime() - date2.getTime());
long difftDays = difference / (24 * 60 * 60 * 1000);
Log.i("Testing","days" +difftDays);
days.setText("days" +difftDays);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
date.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
c1 = Calendar.getInstance();
int mYear = c1.get(Calendar.YEAR); // current year
int mMonth = c1.get(Calendar.MONTH); // current month
int mDay = c1.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(ResourceActivity.this,new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
String[] MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String mon=MONTHS[monthOfYear];
date.setText(dayOfMonth + "-"
+ (mon) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
dateto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// calender class's instance and get current date , month and year from calender
c2 = Calendar.getInstance();
int mYear = c2.get(Calendar.YEAR); // current year
int mMonth = c2.get(Calendar.MONTH); // current month
int mDay = c2.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
datePickerDialog = new DatePickerDialog(ResourceActivity.this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
String[] MONTHS = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
String mon=MONTHS[monthOfYear];
dateto.setText(dayOfMonth + "-" + (mon) + "-" + year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
}
}
android diff days between two dates
Try this
public static long printDifference(Date startDate, Date endDate){
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
return elapsedDays;
}
how to calculate number of days between two dates entered by user through datepicker in android studio
To get Date difference in days first you need to subtract date_to with date_from
like this -
long difference = Math.abs(date_to.getTime() - date_from.getTime());
Then you can get Days difference with below given formula -
int days = (int) (difference / (1000 * 60 * 60 * 24));
How do I get difference between two dates in android?, tried every thing and post
You're close to the right answer, you are getting the difference in milliseconds between those two dates, but when you attempt to construct a date out of that difference, it is assuming you want to create a new Date
object with that difference value as its epoch time. If you're looking for a time in hours, then you would simply need to do some basic arithmetic on that diff
to get the different time parts.
Java:
long diff = date1.getTime() - date2.getTime();
long seconds = diff / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
Kotlin:
val diff: Long = date1.getTime() - date2.getTime()
val seconds = diff / 1000
val minutes = seconds / 60
val hours = minutes / 60
val days = hours / 24
All of this math will simply do integer arithmetic, so it will truncate any decimal points
Related Topics
Android App Crashes After Sdk-Tools Update Version (Noclassdeffound, Tool Version 22)
How to Get Selected Xls File Path from Uri for Sdk 17 or Below for Android
How to Make Edittext Not Focused When Creating Activity
Could Not Find Method in Parent or Ancestor Context
What Is the Use of Memoryfile in Android
Version Control for One-Man Project Using Eclipse
Simple Calculator with Jsp/Servlet and Ajax
How to Use Mockito with Junit5
How to Generate Multiple Lines in PDF Using Apache PDFbox
How to Blur Background Images in Android
Parcelable and Inheritance in Android
Android Studio Build Gradle Outofmemoryerror
Date Format Conversion Android
How Does One Configure Rjava on Osx to Select the Right Jvm -- .Jinit() Failing
How to Escape Apostrophe or Quotes on a Jsp (Used by JavaScript)