我有两个DateTimes,一个是'since'和'now'
的时间我需要的是从那时起。
我的问题是我希望得到它的格式:
实施例: 自''2010年4月17日' 现在='2011年4月15日'
我希望'0年,11个月,29天'
如果是'2010年4月13日',结果应该是: '1年,0个月,2天'
但这种逻辑令我感到困惑。
答案 0 :(得分:4)
我不完全确定我会关注你的问题。这听起来像你想要的:
DateTime since = ...;
DateTime now = ...;
Period period = new Period(since, now, PeriodType.yearMonthDay());
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();
如果不是这样,你能提供更多细节吗?
答案 1 :(得分:1)
下面引用的是来自 home page of Joda-Time 的通知:
<块引用>请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。
使用 java.time
(现代日期时间 API)的解决方案:
Period#between
获取两个 LocalDate
之间的句点。DateTimeFormatter
函数构建 parseCaseInsensitive
。DateTimeFormatter
without a Locale
。演示:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern("d MMMM uuuu")
.toFormatter(Locale.ENGLISH);
LocalDate since = LocalDate.parse("17 april 2010", dtf);
LocalDate now = LocalDate.parse("15 april 2011", dtf);
Period period = Period.between(since, now);
String strPeriod = String.format("%d years %d months %d days", period.getYears(), period.getMonths(),
period.getDays());
System.out.println(strPeriod);
}
}
输出:
0 years 11 months 29 days
从 Trail: Date Time 了解有关现代 Date-Time API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaring 和 How to use ThreeTenABP in Android Project。