【发布时间】:2014-02-15 12:59:12
【问题描述】:
我有计数器,你设置一个日期,然后你可以得到这个日期的时间,但我需要以选择的格式显示它。
例如: 如果我还剩 1 天 13 小时 43 分 30 秒,并将格式设置为:
“你还有:#d# 天,#h# 小时,#m# 分钟死亡”
然后只显示:
“你还有 1 天 13 小时 43 分钟死”
但如果你将格式设置为:
“你还有:#h# 小时,#m# 分钟死亡”
那我需要显示:
“你还有 37 小时 43 分钟的时间去死”
(所以缺少的类型(天)被转换为其他(小时))
我有这个代码: PS:S、M、H、D、W 以毫秒为单位,分钟以毫秒为单位……
public static String getTimerData(long time, String format) {
int seconds = -1, minutes = -1, hours = -1, days = -1, weeks = -1;
if (format.contains("#s#")) {
seconds = (int) (time / S);
}
if (format.contains("#m#")) {
if (seconds == -1) {
minutes = (int) (time / M);
} else {
minutes = (seconds / 60);
seconds %= 60;
}
}
if (format.contains("#h#")) {
if (minutes == -1) {
hours = (int) (time / H);
} else {
hours = (minutes / 60);
minutes %= 60;
}
}
if (format.contains("#d#")) {
if (hours == -1) {
days = (int) (time / D);
} else {
days = (hours / 24);
hours %= 24;
}
}
if (format.contains("#w#")) {
if (days == -1) {
weeks = (int) (time / W);
} else {
weeks = (days / 7);
days %= 7;
}
}
return format.replace("#w#", Integer.toString(weeks)).replace("#d#", Integer.toString(days)).replace("#h#", Integer.toString(hours)).replace("#m#", Integer.toString(minutes)).replace("#s#", Integer.toString(seconds));
}
还有...有更好的方法吗?
【问题讨论】: