Java comparison time differs by several months
Do project today encounter data returning 6 months from the current month
CompareTo method of new characteristic yearmonth of scheme 1::java1.8
Compare the same year, such as the current August 2017, incoming parameters 2017, 2, print: 6
But not in the same year, such as incoming parameters 2016, 2, expected to print: 18, but the actual print is: 1
So continue the test, pass in the parameter 2015, 2, expect to print: 30, but the actual print is: 2
Visible Yearmonth CompareTo method when the return value is a few months in the same year, and when the difference is over a few years, it is not a current requirement.
/**
* Use Yearmonth method CompareTo compare two time difference a few months
* @param year
* @param month month/
public
Void Testyearmonth (int year, int month) {
Yearmonth yearmonth = Yearmonth.of (year, month);
Current month
yearmonth Yearmonthnow = Yearmonth.now ();
int difference = Yearmonthnow.compareto (yearmonth);
SYSTEM.OUT.PRINTLN (difference);
}
Scenario 2: Use calender to compare years, then compare months, the difference between the years multiplied by 12 plus the difference between the month of the total month, resolved.
/**
* Compare time to the current time distance of several months
*
* @param datestr incoming time string, format yyyymmddhhmmss
* * @return * *
private int Comparewithnow (String datestr) {
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm");
String afferentyearmonth = Dateutil.getstringsim (Datestr, "Yyyymmddhhmmss", "yyyy-mm");
String nowyearmonth = Yearmonth.now (). toString ();
Calendar afferent = Calendar.getinstance ();
Calendar now = Calendar.getinstance ();
try {
afferent.settime (Sdf.parse (Afferentyearmonth));
Now.settime (Sdf.parse (Nowyearmonth));
} catch (ParseException e) {
e.printstacktrace ();
}
int year = (Now.get (calendar.year)-Afferent.get (calendar.year)) *;
int month = Now.get (calendar.month)-Afferent.get (calendar.month);
Return Math.Abs (year + month);
}