All Downloads are FREE. Search and download functionalities are using the official Maven repository.

spring.turbo.util.time.DurationParseUtils Maven / Gradle / Ivy

package spring.turbo.util.time;

import org.springframework.boot.convert.DurationStyle;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import spring.turbo.util.Asserts;

import java.time.Duration;
import java.time.temporal.ChronoUnit;

/**
 * {@link Duration} 解析工具
 *
 * @author 应卓
 * @see DurationFormatUtils
 * @since 1.0.1
 */
public final class DurationParseUtils {

    /**
     * 私有构造方法
     */
    private DurationParseUtils() {
    }

    /**
     * 从字符串解析 {@link Duration}
     * 

* 用法: *

    *
  • {@code DurationParseUtils.parse("200ms")}
  • *
  • {@code DurationParseUtils.parse("1h")}
  • *
  • {@code DurationParseUtils.parse("P21D")}
  • *
  • {@code DurationParseUtils.parse("P3Y6M")}
  • *
* * @param string 待解析的字符串 * @return 解析结果 * @throws IllegalArgumentException 字符串格式不正确 */ public static Duration parse(String string) { return parse(string, null); } /** * 从字符串解析 {@link Duration} *

* 用法: *

    *
  • {@code DurationParseUtils.parse("200ms", ChronoUnit.MILLIS)}
  • *
  • {@code DurationParseUtils.parse("1h", ChronoUnit.MILLIS)}
  • *
  • {@code DurationParseUtils.parse("P21D", null)}
  • *
  • {@code DurationParseUtils.parse("P3Y6M", null)}
  • *
* * @param string 待解析的字符串 * @param unit 默认时间单位,可为空,为空时为毫秒 * @return 解析结果 * @throws IllegalArgumentException 字符串格式不正确 */ public static Duration parse(@NonNull String string, @Nullable ChronoUnit unit) { Asserts.notNull(string); Duration duration = parseFromSimpleStyle(string, unit); if (duration == null) { duration = parseFromISO8601Style(string, unit); } if (duration == null) { throw new IllegalArgumentException("'" + string + "' is not a valid duration"); } return duration; } @Nullable private static Duration parseFromSimpleStyle(String string, @Nullable ChronoUnit unit) { try { return DurationStyle.SIMPLE.parse(string, unit); } catch (Exception e) { return null; } } @Nullable private static Duration parseFromISO8601Style(String string, @Nullable ChronoUnit unit) { try { return DurationStyle.ISO8601.parse(string, unit); } catch (Exception e) { return null; } } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy