我需要找出日期(以yyyy-mm-dd格式)与当前日期之间的差异。
我写了一篇关于找出当前日期的信息:
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
Date now = new Date();
String strDate = sdfDate.format(now);
System.out.println("Current date:" + strDate);
String date2 = "2014-01-15";
现在,我想了解strDate
和date2
之间天数的差异。我在堆栈溢出中搜索了一些类似的帖子,但无法找到解决方案。任何帮助都非常值得赞赏。
由于
答案 0 :(得分:0)
这很常见。以下是谷歌的一个例子。
来源:http://www.mkyong.com/java/how-to-calculate-date-time-difference-in-java/
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDifferentExample {
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
//HH converts hour in 24 hours format (0-23), day calculation
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);
//in milliseconds
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.print(diffDays + " days, ");
System.out.print(diffHours + " hours, ");
System.out.print(diffMinutes + " minutes, ");
System.out.print(diffSeconds + " seconds.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 1 :(得分:0)
java.util.Calender
对您非常有帮助。这里有一个例子:
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
Calendar now = Calendar.getInstance();
String strDate2 = "2014-01-15";
Calendar date2 = Calendar.getInstance();
date2.setTimeInMillis(sdfDate.parse(strDate2).getTime());
System.out.println(now.get(Calendar.DATE));
System.out.println(date2.get(Calendar.DATE));