zhoutg 3 лет назад
Родитель
Сommit
c215e5c209
1 измененных файлов с 28 добавлено и 10 удалено
  1. 28 10
      common/src/main/java/com/diagbot/util/AgeUtil.java

+ 28 - 10
common/src/main/java/com/diagbot/util/AgeUtil.java

@@ -30,7 +30,7 @@ public class AgeUtil {
             }
             // X日|天
             if (ageDay(ageStr)) {
-                return getHalfUp((Double.parseDouble(ageStr.substring(0, ageStr.length() - 1))) / 365);
+                return getConvertDouble(ageStr, 1, 365);
             }
             // X岁
             if (ageYear(ageStr)) {
@@ -48,19 +48,21 @@ public class AgeUtil {
                 }
                 return Double.parseDouble(ageArr[0]) + getHalfUp(Double.parseDouble(ageArr[1]) / 12);
             }
-            // X月 | X个月
+            // X月|X个月
             if (ageYue(ageStr)) {
-                String noUnit = "";
                 if (ageStr.endsWith("个月")) {
-                    noUnit = ageStr.substring(0, ageStr.length() - 2);
+                    return getConvertDouble(ageStr, 2, 12);
                 } else {
-                    noUnit = ageStr.substring(0, ageStr.length() - 1);
+                    return getConvertDouble(ageStr, 1, 12);
                 }
-                return getHalfUp(Double.parseDouble(noUnit) / 12);
             }
-            // X时
+            // X小时|
             if (ageHour(ageStr)) {
-                return getHalfUp((Double.parseDouble(ageStr.substring(0, ageStr.length() - 1))) / (365 * 24));
+                if (ageStr.endsWith("小时")) {
+                    return getConvertDouble(ageStr, 2, 365 * 24);
+                } else if (ageStr.endsWith("时")) {
+                    return getConvertDouble(ageStr, 1, 365 * 24);
+                }
             }
             // 特殊值处理
             switch (ageStr) {
@@ -96,6 +98,18 @@ public class AgeUtil {
         return 20.0;
     }
 
+    /**
+     * 获取转换后的数值
+     *
+     * @param ageStr      年龄字符串
+     * @param len         字符串长度
+     * @param denominator 分母
+     * @return
+     */
+    public static Double getConvertDouble(String ageStr, int len, int denominator) {
+        return getHalfUp(Double.parseDouble(ageStr.substring(0, ageStr.length() - len)) / denominator);
+    }
+
     /**
      * 判断字符串是否 仅 包含数字
      *
@@ -151,13 +165,13 @@ public class AgeUtil {
     }
 
     /**
-     * 判断年龄字符串:x时
+     * 判断年龄字符串:x小时|
      *
      * @param str
      * @return
      */
     public static boolean ageHour(String str) {
-        String regex = NUMBER_REGEX + "时";
+        String regex = NUMBER_REGEX + "(小)?时";
         return str.matches(regex);
     }
 
@@ -182,4 +196,8 @@ public class AgeUtil {
         BigDecimal bg = new BigDecimal(String.valueOf(ageStr));
         return bg.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
     }
+
+    public static void main(String[] args) {
+
+    }
 }