有没有更好的方法将某个时间单位添加到 DateTime 对象?
我想做类似的事情:
TimeUnit unit = TimeUnit.valueOf("days");
DateTime date = new DateTime().add(unit, 20);
这是我当前的实现。
int number = 20;
MutableDateTime now = new MutableDateTime();
String timeUnit = getTimeUnit(); // returns "days", "months", "years"
if (timeUnit.equals("days"))
now.addDays(number);
else if (timeUnit.equals("months"))
now.addMonths(number);
else
now.addYears(number);
return now.toDateTime();
最佳答案
Sotirios Delimanolis 的回答是正确的。 JodaTime 没有类似枚举的概念,因为它是在 JDK5 中引入 Java 泛型和枚举之前开发的。在 Java 8 中,您也可以采用这种方式或类似方式:
String name = "days"; // or months or years
ChronoUnit unit = ChronoUnit.valueOf(name.toUpperCase());
LocalDateTime ldt = LocalDateTime.of(...);
ldt = ldt.plus(number, unit);
或者考虑使用 ZonedDateTime
而不是 LocalDateTime
。新方法要优雅得多(是的,JodaTime 变旧了)。
关于java - 将时间单位添加到 Joda DateTime 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20952633/