Parsing time strings like “1h 30min”

前端 未结 6 721
遇见更好的自我
遇见更好的自我 2020-11-29 07:28

Anyone know of a Java library that can parse time strings such as \"30min\" or \"2h 15min\" or \"2d 15h 30min\" as milliseconds (or some kind of Duration object). Can Joda-T

6条回答
  •  情书的邮戳
    2020-11-29 07:58

    FYI, Just wrote this for hour+ periods, only uses java.time.*, pretty simple to understand and customize for any need;

    This version works with strings like; 3d12h, 2y, 9m10d, etc.

    import java.time.Duration;
    import java.time.Instant;
    import java.time.Period;
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    import java.util.Locale;
    
    private static final Pattern periodPattern = Pattern.compile("([0-9]+)([hdwmy])");
    
    public static Long parsePeriod(String period){
        if(period == null) return null;
        period = period.toLowerCase(Locale.ENGLISH);
        Matcher matcher = periodPattern.matcher(period);
        Instant instant=Instant.EPOCH;
        while(matcher.find()){
            int num = Integer.parseInt(matcher.group(1));
            String typ = matcher.group(2);
            switch (typ) {
                case "h":
                    instant=instant.plus(Duration.ofHours(num));
                    break;
                case "d":
                    instant=instant.plus(Duration.ofDays(num));
                    break;
                case "w":
                    instant=instant.plus(Period.ofWeeks(num));
                    break;
                case "m":
                    instant=instant.plus(Period.ofMonths(num));
                    break;
                case "y":
                    instant=instant.plus(Period.ofYears(num));
                    break;
            }
        }
        return instant.toEpochMilli();
    }
    
    

提交回复
热议问题