【问题标题】:Converting org.joda.time.Period to java.time.Period将 org.joda.time.Period 转换为 java.time.Period
【发布时间】:2017-11-10 06:47:46
【问题描述】:

我正在尝试用 java.time 替换 org.joda.time.Period。

我们在 DB 中存储了以下值。

P1M, P1Y, P1D, PT1H, PT1M

只是为了解析这个值,

Period monthly = ISOPeriodFormat.standard().parsePeriod(<One of the above value from DB>);

这很简单,并且按预期获得 Period 。但是,现在换成 java.time 就麻烦了。

因为,P1D, P1M, P1Y 应该使用下面的代码来解析,

java.time.Period period = java.time.Period.parse("P1M");

并且,P1H and P1D 应该使用下面的代码进行解析。

Duration dailyD = Duration.parse("P1D");

所以,我可能还需要一些字符串检查,例如,

if(value.startsWith("PT")) {
   // Use java.time.Duration
} else {
   // Use java.time.Period
}

这个逻辑有更好的代码吗?

另外,最后,我必须根据上面的 java.time.Period 或 java.time.Duration 找到从某个 startTime 到截止日期的发生次数。

比如,如果 startDateTime 是01/01/2015 08:30

LocalDateTime startDateTime = // the above startDateTime ..

    if(value.startsWith("PT")) {
       // Use java.time.Duration
     ChronoUnit.SECONDS.between(startDateTime,curentDate)/(duration.toMillis()/1000)
    } else {

 if(value.endsWith("Y")) {
       // Use java.time.Period
ChronoUnit.YEARS.between(startDateTime,curentDate)/(period.getYears()/1000)
} else if(value.endsWith("M")){
 ChronoUnit.MONTHS.between(startDateTime,curentDate)/(period.getMonths()/1000)
}

没有这个值解析还有其他更好的方法吗?

我的输入可能有 P2M、P10M、P2Y、PT15M、PT10M。它不会像 P1MT10M 那样同时具有周期和时间的组合。但可以是任意数量的月、年或天。

【问题讨论】:

  • 我不认为您打算在最后一次代码 sn-p 中除以 1000 的最后两次,分别是年份和月份。
  • 您可能想在 ThreeTen Extra 项目中查看org.threeten.extra.PeriodDuration
  • 我想(像你一样?)我宁愿把所有的解析都留给库方法。一种选择是尝试同时解析为PeriodDuration,然后选择一个可行的。
  • 您确定您的经期始终是Period 还是Duration?或者反过来说,P1MT1H 之类的内容是否会出现在您的数据中?

标签: java java-time


【解决方案1】:

Java-8 没有像 org.joda.time.Period 这样复杂的持续时间类型。但是您可以直接创建自己的接口TemporalAmount 实现:

import java.time.DateTimeException;    
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalUnit;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import static java.time.temporal.ChronoUnit.*;

public class SimpleDuration implements TemporalAmount {

    private static final List<TemporalUnit> SUPPORTED_UNITS =
        Collections.unmodifiableList(Arrays.asList(YEARS, MONTHS, DAYS, HOURS, MINUTES));

    private final int amount;
    private final ChronoUnit unit;

    private SimpleDuration(int amount, ChronoUnit unit) {
        this.amount = amount;
        this.unit = unit;
    }

    public static SimpleDuration of(int amount, ChronoUnit unit) {
        if (SUPPORTED_UNITS.contains(unit)) {
            return new SimpleDuration(amount, unit);
        } else {
            throw new IllegalArgumentException("Not supported: " + unit);
        }
    }

    @Override
    public long get(TemporalUnit unit) {
        if (this.unit.equals(unit)) {
          return this.amount;
        }
        return 0;
    }

    @Override
    public List<TemporalUnit> getUnits() {
        return SUPPORTED_UNITS;
    }

    @Override
    public Temporal addTo(Temporal temporal) {
        return temporal.plus(this.amount, this.unit);
    }

    @Override
    public Temporal subtractFrom(Temporal temporal) {
        return temporal.minus(this.amount, this.unit);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof SimpleDuration) {
            SimpleDuration that = (SimpleDuration) obj;
            return this.unit == that.unit && this.amount == that.amount;
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return this.unit.hashCode() + 37 * Integer.hashCode(this.amount);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        if (this.amount < 0) {
            sb.append('-');
        }
        sb.append('P');
        if (this.unit.isTimeBased()) {
            sb.append('T');
        }
        sb.append(Math.abs(this.amount));
        switch (this.unit) {

            case YEARS :
                sb.append('Y');
                break;

            case MONTHS :
                sb.append('M');
                break;

            case DAYS :
                sb.append('D');
                break;

            case HOURS :
                sb.append('H');
                break;

            case MINUTES :
                sb.append('M');
                break;

            default :
                throw new UnsupportedOperationException(this.unit.name());
        }
        return sb.toString();
    }

    public static SimpleDuration parse(String input) {
        int len = input.length();
        int index = 0;
        boolean negative = false;
        if (len > 0 && input.charAt(0) == '-') {
            negative = true; // for XML-Schema (not for ISO-8601)
            index++;
        }
        if (len >= 3 && input.charAt(index) == 'P') {
            boolean timeBased = (input.charAt(index + 1) == 'T');
            char last = input.charAt(len - 1);
            ChronoUnit unit;
            switch (last) {

                case 'Y' :
                    unit = YEARS;
                    break;

                case 'M' :
                    unit = (timeBased ? MINUTES : MONTHS);
                    break;

                case 'D' :
                    unit = DAYS;
                    break;

                case 'H' :
                    unit = HOURS;
                    break;

                default :
                    throw new DateTimeException(
                        "Unknown unit symbol found at last position: " + input
                    );
            }
            if (unit.isTimeBased() != timeBased) {
                throw new DateTimeException("Invalid XML-Schema-format: " + input);
            }
            try {
              int amount =
                Integer.parseInt(
                  input.substring(index).substring(timeBased ? 2 : 1, len - 1 - index));
              if (amount < 0) {
                throw new DateTimeException(
                  "XML-Schema does not allow negative amounts inside: " + input);
              }
              return SimpleDuration.of(negative ? -amount : amount, unit);
            } catch (NumberFormatException ex) {
                throw new DateTimeException("Invalid XML-Schema-format: " + input, ex);
            }
        }
        throw new DateTimeException("Cannot parse: " + input);
    }

    public static void main(String... args) {
        System.out.println(parse("-PT10M")); // -PT10M
    }
}

【讨论】:

  • 感谢您的意见。但是,我的输入可能有 P2M、P10M、P2Y、PT15M、PT10M。它不会像 P1MT10M 那样同时具有周期和时间的组合。但可以是任意数量的月、年或天。
  • @user1578872 好吧,那是您在原始问题中以不同方式告诉我们的内容。我很快就会根据您的新要求调整我的答案。
  • @user1578872 现在已经调整了我的答案。建议的代码涵盖适用于您提到的表示的 XML 模式的简化变体,包括负持续时间的可能前导减号。
  • 太棒了。希望 ChronoException 可以替换为 RuntimeException 因为我不想导入 net.time4j.engine。
  • @assylias PeriodDurationof Threeten-extra 不一样(在负持续时间的情况下不适合 XML 模式),net.time4j.Duration 对于负持续时间甚至有不同的算术行为,并且有额外的格式化功能(在threeten-extra 中缺少)所以我们在这里讨论苹果和橙子,而不是真正可比较或可交换的类,代表时间量。并且 OP 已明确要求 Java-8 解决方案,而不是第 3 方库。
猜你喜欢
  • 1970-01-01
  • 2021-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 1970-01-01
  • 2014-07-20
相关资源
最近更新 更多