要确定两个日期之间的天数,我们可以使用 Java Calendar 类。让我们演示如何使用它来计算当前日期与格式为 yyyy-mm-dd 的指定日期之间的差异。
Calendar today = Calendar.getInstance(); String specifiedDate = "2010-08-25"; // Parse the specified date string int year = Integer.parseInt(specifiedDate.substring(0, 4)); int month = Integer.parseInt(specifiedDate.substring(5, 7)) - 1; // Months are zero-indexed int day = Integer.parseInt(specifiedDate.substring(8, 10)); Calendar thatDay = Calendar.getInstance(); thatDay.set(year, month, day); // Calculate the difference in milliseconds long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); // Convert milliseconds to days double days = diff / (24 * 60 * 60 * 1000); System.out.println("Number of days between today and " + specifiedDate + ": " + days);
注意:
上述方法提供了粗略的计算,一般不建议仅仅依赖它。为了更准确的日期处理和操作,请考虑使用 JodaTime 库,它提供了一组更全面的日期相关操作。
以上是如何使用Java计算两个日期之间的天数差异?的详细内容。更多信息请关注PHP中文网其他相关文章!