我有两个约会.如何分辨这两个日期之间的天数差异?
我听说过SimpleDateFormat,但是我不知道如何使用它.
我尝试了这个:
String fromdate = "Apr 10 2011";
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("MMM DD YYYY");
sdf.parse(fromdate);
Calendar cal = Calendar.getInstance();
cal.setTime(sdf);
我也试过这个:
String date1 = "APR 11 2011";
String date2 = "JUN 02 2011";
String format = "MMM DD 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));
System.out.println(diffDays);
但出现异常“非法图案字符’Y’”.
解决方法:
其他答案是正确的,但已过时.
java.time
Java 8和更高版本内置了java.time框架.这些类取代了以前麻烦的日期时间类,例如java.util.Date,.Calendar和& java.text.SimpleDateFormat. Joda-Time小组还建议迁移到java.time.
要了解更多信息,请参见Oracle Tutorial.并在Stack Overflow中搜索许多示例和说明.
许多java.time功能都被反向移植到Java 6& ThreeTen-Backport中的版本7,并进一步适用于ThreeTenABP中的Android.
ThreeTen-Extra项目使用其他类扩展了java.time.该项目为将来可能在java.time中添加内容提供了一个试验场.
本地日期
LocalDate
类表示不带日期和时区的仅日期值.
我建议在可能的情况下为字符串使用标准的ISO 8601格式.但是在您的情况下,我们需要指定一种格式设置模式.
String input = "Apr 10 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu" );
LocalDate earlier = LocalDate.parse ( input , f );
DateTimeFormatter formatterOut = DateTimeFormatter.ofLocalizedDate ( FormatStyle.MEDIUM ).withLocale ( Locale.US );
String output = earlier.format ( formatterOut );
LocalDate later = earlier.plusDays ( 13 );
long days = ChronoUnit.DAYS.between ( earlier , later );
转储到控制台.
System.out.println ( "from earlier: " + earlier + " to later: " + later + " = days: " + days + " ending: " + output );
from earlier: 2011-04-10 to later: 2011-04-23 = days: 13 ending: Apr 10, 2011