package com.isu.gaswellwatch.vo.command; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import java.security.InvalidParameterException; import java.time.LocalTime; import java.util.Objects; /** * @author 王仕龙 * 2024/11/26 21:08 */ public interface Timing { default String timeValidate(String time, String name, int maxHours) { if (StringUtils.isBlank(time)) { throw new NullPointerException(name + " cannot be empty"); } if (!StringUtils.contains(time, ":")) { throw new InvalidParameterException(name + " is invalid. Valid format: [0-" + maxHours + "]:[0-59]:[0-59]"); } String[] times = StringUtils.split(time, ":"); int hour = 0, minute = 0, second = 0; if (times.length == 1) { hour = NumberUtils.createInteger(times[0]); } else if (times.length == 2) { hour = NumberUtils.createInteger(times[0]); minute = NumberUtils.createInteger(times[1]); } else if (times.length == 3) { hour = NumberUtils.createInteger(times[0]); minute = NumberUtils.createInteger(times[1]); second = NumberUtils.createInteger(times[2]); } else { throw new InvalidParameterException(name + " is invalid. Valid format: [0-" + maxHours + "]:[0-59]:[0-59]"); } if (!(hour >= 0 && hour <= maxHours && minute >= 0 && minute <= 59 && second >= 0 && second <= 59)) { throw new InvalidParameterException(name + " is invalid. Valid format: [0-" + maxHours + "]:[0-59]:[0-59]"); } return StringUtils.joinWith(":", StringUtils.leftPad(String.valueOf(hour), 2, "0"), StringUtils.leftPad(String.valueOf(minute), 2, "0"), StringUtils.leftPad(String.valueOf(minute), 2, "0")); } default String timerValidate(String time, String name) { return this.timeValidate(time, name, 23); } default String timingValidate(String time, String name) { return this.timeValidate(time, name, 999); } default String toHexString(LocalTime time) { return Objects.equals(LocalTime.MIN, time) ? "000000000000" : Objects.equals(LocalTime.MAX, time) ? "0017003B003B" : this.toHexString(time.toString()); } /** * 支持:[0-999]:[0-59]:[0-59] * * @param stringTime * @return */ default String toHexString(String stringTime) { if (StringUtils.equals(stringTime, "00:00") || StringUtils.equals(stringTime, "00:00:00")) { return "000000000000"; } if (StringUtils.equals(stringTime, "23:59:59")) { return "0017003B003B"; } if (StringUtils.equals(stringTime, "999:59:59")) { return "03E7003B003B"; } String[] items = StringUtils.split(stringTime, ":"); int hours = Integer.parseInt(items[0]); int minutes = items.length < 2 ? 0 : Integer.parseInt(items[1]); int seconds = items.length < 3 ? 0 : Integer.parseInt(items[2]); return StringUtils.leftPad(Integer.toHexString(hours), 4, "0") + StringUtils.leftPad(Integer.toHexString(minutes), 4, "0") + StringUtils.leftPad(Integer.toHexString(seconds), 4, "0"); } }