I want to create a convenient method to calculate the difference in days
Receives string date information as an argument
→ For example, `2018/01/01``` and
`2018/01/20```
→ Returns the difference of the date received as an argument as an integer
public static int dateDiff(String dateFromStrig, String dateToString) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date dateTo = null;
Date dateFrom = null;
//Convert to Date type
try {
dateFrom = sdf.parse(dateFromStrig);
dateTo = sdf.parse(dateToString);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
//Calculate the number of days of difference
long dateTimeTo = dateTo.getTime();
long dateTimeFrom = dateFrom.getTime();
long dayDiff = ( dateTimeTo - dateTimeFrom ) / (1000 * 60 * 60 * 24 );
System.out.println( "Difference days: " + dayDiff );
return (int) dayDiff;
}
Recommended Posts