我有两个日期,例如19/03/1950和18/04/2011。我如何计算它们之间的差异以获得该人的年龄?我是否必须继续乘以得到小时或秒等?
答案 0 :(得分:5)
String date1 = "26/02/2011";
String date2 = "27/02/2011";
String format = "dd/MM/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date dateObj1 = sdf.parse(date1);
Date dateObj2 = sdf.parse(date2);
long diff = dateObj2.getTime() - dateObj1.getTime();
int diffDays = (int) (diff / (24* 1000 * 60 * 60));
答案 1 :(得分:1)
您使用类日期和持续时间:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/Date.html
http://download.oracle.com/javase/1.5.0/docs/api/javax/xml/datatype/Duration.html
您可以创建Date对象,然后使用Duration的方法addTo()和subtract()
答案 2 :(得分:1)
以下代码将为您提供两个日期之间的区别:
import java.util.Date;
import java.util.GregorianCalendar;
public class DateDiff {
public static void main(String[] av) {
/** The date at the end of the last century */
Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();
/** Today's date */
Date today = new Date();
// Get msec from each, and subtract.
long diff = today.getTime() - d1.getTime();
System.out.println("The 21st century (up to " + today + ") is "
+ (diff / (1000 * 60 * 60 * 24)) + " days old.");
}
}
答案 3 :(得分:1)
为什么不使用jodatime?在java中计算日期和时间要容易得多。
您可以获取年份并使用方法yearsBetween()