计算日期之间的天数差异

在我的代码中,日期之间的差异是错误的,因为它应该是38天而不是8天。 我该怎么办?

package random04diferencadata; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Random04DiferencaData { /** * http://www.guj.com.br/java/9440-diferenca-entre-datas */ public static void main(String[] args) { SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/mm/yyyy"); try { Date date1 = sdf.parse("00:00 02/11/2012"); Date date2 = sdf.parse("10:23 10/12/2012"); long differenceMilliSeconds = date2.getTime() - date1.getTime(); System.out.println("diferenca em milisegundos: " + differenceMilliSeconds); System.out.println("diferenca em segundos: " + (differenceMilliSeconds / 1000)); System.out.println("diferenca em minutos: " + (differenceMilliSeconds / 1000 / 60)); System.out.println("diferenca em horas: " + (differenceMilliSeconds / 1000 / 60 / 60)); System.out.println("diferenca em dias: " + (differenceMilliSeconds / 1000 / 60 / 60 / 24)); } catch (ParseException e) { e.printStackTrace(); } } } 

问题出在SimpleDateFormat变量中。 几个月由Capital M.代表。

尝试更改为:

 SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy"); 

有关更多信息,请参阅此javadoc。

编辑:

如果您想以您评论的方式打印差异,这里是代码:

  SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy"); try { Date date1 = sdf.parse("00:00 02/11/2012"); Date date2 = sdf.parse("10:23 10/12/2012"); long differenceMilliSeconds = date2.getTime() - date1.getTime(); long days = differenceMilliSeconds / 1000 / 60 / 60 / 24; long hours = (differenceMilliSeconds % ( 1000 * 60 * 60 * 24)) / 1000 / 60 / 60; long minutes = (differenceMilliSeconds % ( 1000 * 60 * 60)) / 1000 / 60; System.out.println(days+" days, " + hours + " hours, " + minutes + " minutes."); } catch (ParseException e) { e.printStackTrace(); } 

希望这对你有所帮助!