快速提问。
是否有更聪明/更时尚的方式将分钟转换为更易读的格式,仅显示最高有效数字?
我正在使用Android Studio的Java。
public String MinutesToHumanReadable(Long minutes) {
...
}
即
2 mins = "2 mins"
45 mins = "45 mins"
60 mins = ">1 hr"
85 mins = ">1 hr"
120 mins = ">2 hrs"
200 mins = ">3 hrs"
1500 mins = ">1 day"
我的代码非常繁琐,草率,并且有些难以理解。
public String MinutesToHumanReadable(long minutes) {
String sReturn = "";
if (minutes > 515600) {
sReturn = "> 1 yr";
} else if (minutes > 43200) {
sReturn = (minutes / 43200) + " mths";
} else if (minutes > 10080) {
sReturn = (minutes / 10080) + " wks";
} else if (minutes > 1440) {
sReturn = (minutes / 1440) + " days";
} else if (minutes > 60) {
sReturn = (minutes / 60) + " hrs";
} else {
//<60
sReturn = minutes + " mins";
}
return sReturn;
}
非常感谢,
Ĵ
最佳答案
好吧,有可能,我想出了,我为此感到骄傲! :)
请注意,仅通过更改这两个数组中的值,就可以轻松添加任何其他值而无需更改方法本身。例如,如果“年”不足以满足您的需求,则可以添加“十年”和“百年” ...
如果您的输出值超过1,则此代码还将在末尾添加“s”字母。
public class SuperMinutesChangerClass {
public static int[] barriers = {1, 60, 60*24, 60*24*7, 60*24*365, Integer.MAX_VALUE};
public static String[] text = {"min", "hr", "day", "week", "year"};
public static String minutesToHumanReadable(int minutes){
String toReturn = "";
for (int i = 1; i < barriers.length; i++) {
if (minutes < barriers[i]){
int ammount = (minutes/barriers[i-1]);
toReturn = ">" + (ammount) + " " + text[i-1];
if (ammount > 1){
toReturn += "s";
}
break;
}
}
return toReturn;
}
}
样本输入:
public static void main(String[] args) {
System.out.println(minutesToHumanReadable(10));
System.out.println(minutesToHumanReadable(60));
System.out.println(minutesToHumanReadable(61));
System.out.println(minutesToHumanReadable(121));
System.out.println(minutesToHumanReadable(8887));
System.out.println(minutesToHumanReadable(9999743));
}
输出为:
>10 mins
>1 hr
>1 hr
>2 hrs
>6 days
>19 years