Java 以字符串格式计算两个日期之间的日期差
我有两个字符串格式的日期。我需要以天为单位获得这两个日期之间的差异。我如何获得它?我对这些日期格式非常陌生。请给我任何建议Java 以字符串格式计算两个日期之间的日期差,java,Java,我有两个字符串格式的日期。我需要以天为单位获得这两个日期之间的差异。我如何获得它?我对这些日期格式非常陌生。请给我任何建议 2017-06-13 2017-06-27 String newDate = null; Date dtDob = new Date(GoalSelectionToDate); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); newDate = sdf.format(dt
2017-06-13
2017-06-27
String newDate = null;
Date dtDob = new Date(GoalSelectionToDate);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
newDate = sdf.format(dtDob);
String newDate1 = null;
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
newDate1 = sdf1.format(currentDate);
System.out.println("currentdateformat"+newDate1);
System.out.println("anotherdateformat"+newDate);
见下文
import java.time.LocalDate;
import java.time.Period;
public class DatesComparison {
public static void main(String[] args) {
String date1= "2017-06-13";
String date2= "2017-06-27";
LocalDate localDate1 = LocalDate.parse(date1);
LocalDate localDate2 = LocalDate.parse(date2);
Period intervalPeriod = Period.between(localDate1, localDate2);
System.out.println("Difference of days: " + intervalPeriod.getDays()); // Difference of days: 14
System.out.println("Difference of months: " + intervalPeriod.getMonths()); // Difference of months: 0
System.out.println("Difference of years: " + intervalPeriod.getYears()); // Difference of years: 0
}
}
如果您使用的是Java 8,则无需格式化程序即可解析,因为它们是ISO格式:
LocalDate start = LocalDate.parse("2017-06-13");
LocalDate end = LocalDate.parse("2017-06-27");
然后,您可以使用以下公式计算它们之间的天数:
这有帮助吗?可能重复的“请参见下文”不是一个有用的答案解释。@JoseZevallos您并没有真正回答这个问题-特别是,如果差异超过一个月,getDays将不会返回两个日期之间的天数。
long days = ChronoUnit.DAYS.between(start, end);