如何从字符串提取多个TimeUnit并转毫秒用于Minecraft权限有效期计算
实现方案
核心思路
通过正则表达式批量捕获字符串中的「数值+时间单位」组合,匹配后映射为对应毫秒值累加即可。
具体实现步骤
- 第一步:预定义时间单位和毫秒值的映射关系,你可以根据需求扩展支持的单位
- 第二步:编写正则匹配规则,一次性捕获所有合法的数值+单位组合
- 第三步:遍历所有匹配结果,逐组计算毫秒值并累加得到总时长
- 第四步:最终到期时间直接按
System.currentTimeMillis() + 总毫秒数计算即可
代码示例(Java,适配你当前的API使用场景)
import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TimeParser { // 单位到毫秒的映射,可自行扩展 private static final Map<Character, Long> UNIT_MILLIS = new HashMap<>(); private static final Pattern TIME_PATTERN = Pattern.compile("(\\d+)([wdhms])", Pattern.CASE_INSENSITIVE); static { UNIT_MILLIS.put('s', 1000L); // 秒 UNIT_MILLIS.put('m', 60 * 1000L); // 分钟 UNIT_MILLIS.put('h', 60 * 60 * 1000L); // 小时 UNIT_MILLIS.put('d', 24 * 60 * 60 * 1000L); // 天 UNIT_MILLIS.put('w', 7 * 24 * 60 * 60 * 1000L); // 周 // 如需支持年/月可以自行添加:注意自然月/年是变动时长,固定时长可按30天/365天计算 // UNIT_MILLIS.put('M', 30 * 24 * 60 * 60 * 1000L); // UNIT_MILLIS.put('y', 365 * 24 * 60 * 60 * 1000L); } public static long parseTimeToMillis(String timeStr) { if (timeStr == null || timeStr.isBlank()) { throw new IllegalArgumentException("时间字符串不能为空"); } Matcher matcher = TIME_PATTERN.matcher(timeStr.toLowerCase()); long totalMillis = 0; int lastMatchEnd = 0; while (matcher.find()) { // 检查是否有非法字符在匹配项之间 if (matcher.start() != lastMatchEnd) { throw new IllegalArgumentException("非法的时间格式:" + timeStr); } long num = Long.parseLong(matcher.group(1)); char unit = matcher.group(2).charAt(0); totalMillis += num * UNIT_MILLIS.get(unit); lastMatchEnd = matcher.end(); } // 检查是否有剩余未匹配的非法字符 if (lastMatchEnd != timeStr.length()) { throw new IllegalArgumentException("非法的时间格式:" + timeStr); } return totalMillis; } // 使用示例 public static void main(String[] args) { String testStr = "4w5d"; long timeInMillis = parseTimeToMillis(testStr); long expireTime = System.currentTimeMillis() + timeInMillis; System.out.println("到期时间戳:" + expireTime); } }
异常处理说明
代码中已经内置了格式校验,如果用户输入非法格式(比如包含4x、abc之类的非标准时间字符串)会直接抛出参数异常,你可以在命令执行逻辑中捕获该异常,给用户返回格式错误提示即可。
内容的提问来源于stack exchange,提问作者iLalox
相关产品推荐
相关产品推荐

