我正在尝试编写代码,以便在月份为31天时找到它工作的两个日期之间的日差异,但是当月份有30天时,结果会减少1天,这个案例有29天,28天月减去2,3天我希望我能知道为什么 代码:
public int dateAfterMod (Calendar endDate){
//TO GET THE CURRENT DATE
GregorianCalendar currentDate = new GregorianCalendar ();
currentDate=(GregorianCalendar) endDate;
//THE CAL.ADD BECUSE THE 1ST MONTH IN THE YEAR IS 0 NOT 1
currentDate.add(Calendar.MONTH, 1);
//TO SET THE DATE TO THE FIRST DAY IN THE MOTH FOR COMPAISSON
currentDate.set(Calendar.DAY_OF_MONTH, 1);
//TO SET THE START DATE WICH IS 1/1/2013
GregorianCalendar startDate = new GregorianCalendar(2013, 1, 1);
//TO FIND THE DIFF BETWEEN THE START DATE AND CUREENT DATE
long diff=(((currentDate.getTimeInMillis()-
startDate.getTimeInMillis())/(1000*60*60*24)));
答案 0 :(得分:0)
试试这种方式
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
System.out.print(Days.daysBetween(dt1, dt2).getDays() + " days, ");
System.out.print(Hours.hoursBetween(dt1, dt2).getHours() % 24 + " hours, ");
System.out.print(Minutes.minutesBetween(dt1, dt2).getMinutes() % 60 + " minutes, ");
System.out.print(Seconds.secondsBetween(dt1, dt2).getSeconds() % 60 + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
<强>输出强>
1 days, 1 hours, 1 minutes, 50 seconds.