ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

TimeUtils记录

TimeUtils记录
/* long milliseconds = 1500L; Log.d("Time", "四舍五入: " + TimeUtils.millisToSecondsRounded(milliseconds)); // 输出 2 Log.d("Time", "截断取整: " + TimeUtils.millisToSecondsTruncated(milliseconds)); // 输出 1 Log.d("Time", "向上取整: " + TimeUtils.millisToSecondsCeil(milliseconds)); // 输出 2 */ public class TimeUtils { // 四舍五入 public static long millisToSecondsRounded(long millis) { return Math.round(millis / 1000.0); } // 截断取整 public static long millisToSecondsTruncated(long millis) { return millis / 1000; } // 向上取整 public static long millisToSecondsCeil(long millis) { return (long) Math.ceil(millis / 1000.0); } /** * 将字符串灵活转换为毫秒时间戳 * @param input 可能是日期时间字符串(如 "2026-07-23 06:00:08")或数字字符串(如 "1758492008000") * @return 毫秒时间戳 * @throws IllegalArgumentException 如果无法解析 */ public static long toMilliseconds(String input) { if (StringUtils.isEmpty(input)) { return 0; } // 1. 尝试当作数字(时间戳)处理 if (isNumeric(input)) { try { return ensureMillisTimestamp(Long.parseLong(input)); // 改为调用新方法 } catch (NumberFormatException e) { throw new IllegalArgumentException("无法解析为时间戳数字: " + input, e); } } // 2. 否则按日期时间格式解析 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); try { LocalDateTime ldt = LocalDateTime.parse(input, formatter); // 使用系统默认时区转时间戳 return ldt.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); } catch (DateTimeParseException e) { throw new IllegalArgumentException("无法解析日期时间字符串: " + input, e); } } public static String toMillisecondsStr(String input) { return toMilliseconds(input) + ""; } /** * 确保时间戳是毫秒级,如果不是(如秒级10位),则自动转为毫秒级 * <p> * 判断逻辑:时间戳值小于 1000000000000L(10^12)视为秒级,乘以1000转为毫秒; * 大于等于该阈值的视为已是毫秒级,直接返回。 * * @param timestamp 时间戳,可能是秒级(10位)或毫秒级(13位) * @return 毫秒级时间戳 */ public static long ensureMillisTimestamp(long timestamp) { if (timestamp <= 0) { return timestamp; } // 小于 10^12 认为是秒级时间戳,乘以 1000 转为毫秒 if (timestamp < 1000000000000L) { return timestamp * 1000; } return timestamp; } /** * 确保时间戳是毫秒级(String版本) * <p> * 先将字符串解析为 long,再调用 {@link #ensureMillisTimestamp(long)} 进行转换。 * * @param timestampStr 时间戳字符串,可能是秒级(10位)或毫秒级(13位) * @return 毫秒级时间戳,解析失败返回 0 */ public static long ensureMillisTimestamp(String timestampStr) { if (StringUtils.isEmpty(timestampStr)) { return 0; } try { long timestamp = Long.parseLong(timestampStr.trim()); return ensureMillisTimestamp(timestamp); } catch (NumberFormatException e) { return 0; } } /** * 支持指定时区的版本 * @param input 同上 * @param zoneId 时区ID,如 "Asia/Shanghai"、"UTC" * @return 毫秒时间戳 */ public static long toMilliseconds(String input, String zoneId) { if (isNumeric(input)) { return Long.parseLong(input); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime ldt = LocalDateTime.parse(input, formatter); return ldt.atZone(ZoneId.of(zoneId)).toInstant().toEpochMilli(); } // 辅助方法:判断字符串是否表示整数(允许负号) private static boolean isNumeric(String str) { if (str == null || str.isEmpty()) return false; int start = (str.charAt(0) == '-') ? 1 : 0; for (int i = start; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** * 计算年龄最正确的方式是用 LocalDate + Period,而不是时间戳相减 * @param birthday 2025-7-5 * @return */ public static int calculateAge(String birthday) { try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDate birthDate = LocalDate.parse(birthday, formatter); // 以“今天”为基准计算年龄 LocalDate today = LocalDate.now(); return Period.between(birthDate, today).getYears(); } catch (Exception e) { return -1; } } }

毫秒转秒取整

在 Java 或 Android 中,将毫秒转换为秒并取整(四舍五入或直接截断)可以通过以下方式实现:


1. 四舍五入取整

long milliseconds = 12345L; // 示例毫秒值 long seconds = Math.round(milliseconds / 1000.0); // 四舍五入
  • 说明:
  • Math.round() 对浮点数结果进行四舍五入。
  • 除以 1000.0 确保结果是浮点数(避免整数除法截断)。

2. 直接截断取整(向下取整)

long milliseconds = 12345L; long seconds = milliseconds / 1000; // 直接截断
  • 说明:
  • 整数除法会自动丢弃小数部分(相当于 Math.floor())。

3. 向上取整

long milliseconds = 12345L; long seconds = (long) Math.ceil(milliseconds / 1000.0); // 向上取整

注意事项

  • 精度问题:

如果毫秒值是 int 类型,注意避免整数溢出(例如使用 long 存储大数值)。

  • 负数处理:

上述方法同样适用于负数(例如 -1500ms 会转换为 -1s 或 -2s,取决于取整方式)

返回列表