java 如何计算两个日期之间的差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5194216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:54:14  来源:igfitidea点击:

How can I calculate the difference between two dates

java

提问by code511788465541441

Possible Duplicate:
How do I calculate someone's age in Java?

可能的重复:
如何在 Java 中计算某人的年龄?

I have two dates eg 19/03/1950 and 18/04/2011. how can i calculate the difference between them to get the person's age? do I have to keep multiplying to get the hours or seconds etc?

我有两个日期,例如 19/03/1950 和 18/04/2011。我怎样才能计算他们之间的差异来得到这个人的年龄?我必须继续乘以得到小时或秒等吗?

回答by Bala R

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));

回答by Bernd Elkemann

You use the classes Date and Duration:

您使用类 Date 和 Duration:

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

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

You create Date-objects, then use Duration's methods addTo() and subtract()

您创建日期对象,然后使用 Duration 的方法 addTo() 和 minus()

回答by Umesh K

The following code will give you difference between two dates:

以下代码将为您提供两个日期之间的差异:

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.");
  }
}

回答by Fredrik

Why not use jodatime? It's much easier to calculate date and time in java.

为什么不使用jodatime?在java中计算日期和时间要容易得多。

You can get the year and use the method yearsBetween()

您可以获取年份并使用该方法 yearsBetween()