在我的代码中,日期之间的差异是错误的,因为它应该是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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于SimpleDateFormat变量.几个月由Capital M.代表.
尝试更改为:
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm dd/MM/yyyy");
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅此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();
}
Run Code Online (Sandbox Code Playgroud)
希望这对你有所帮助!
| 归档时间: |
|
| 查看次数: |
1153 次 |
| 最近记录: |