当前位置: 首页 > news >正文

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,取决于取整方式)

http://www.jsqmd.com/news/1353991/

相关文章:

  • 2026.8月衡水防水补漏维修,卫生间,阳台,外墙,屋顶,地下室漏水根治测评 - 超人防水
  • 2026南阳厂房防水补漏三品牌公开参数与场景对照:工艺/材料/报价/质保(捷修/宅乐安/居固安) - 家居避坑指南
  • 沉浸式电气火灾安全教育系统解析与应用
  • 机器学习模型创建与调用全流程:从数据准备到生产部署
  • 口碑出圈!靠谱AI获客系统源头厂商怎么选? - 品牌品鉴馆
  • Python多任务并行处理实战:线程、进程与协程性能优化指南
  • hacker-slides开发指南:深入了解项目架构与代码实现
  • AI编程助手如何通过Agent Skills实现工程纪律与代码规范
  • Python+OpenClaw实现财务自动化:Excel处理与Agent自治
  • Steam挂刀行情站终极指南:24小时自动追踪四大平台饰品价格的完整教程
  • Navicat重置脚本终极指南:macOS无限试用方案完整解析
  • 从Function Calling到MCP:AI Agent工具调用的三层境界与生产级实践
  • 免费获取高分辨率转录图谱:ProCapNet本地部署与批量处理教程
  • 2026 年8月 甘肃口碑最好的旅行社 **,纯玩合规稳居西北 - 跟我去旅游
  • 2026.8月邢台防水补漏维修,卫生间,阳台,外墙,屋顶,地下室漏水根治测评 - 超人防水
  • 深入解析Hisat2比对日志:从核心指标到RNA-seq数据质控实战
  • 如何用jCodeMunch-MCP节省95%AI代码检索token成本:智能助手的终极解决方案
  • LaTeX数学公式排版指南:从基础语法到实战避坑
  • 2026 金华靠谱准时模具厂深度测评|永康 30 年老牌一站式塑胶模具定制厂家甄选指南 - 闽地观察实事
  • 2026年8月揭晓!专业苏州轻质砖隔墙口碑榜,哪家能拔头筹? - 产品评测官
  • GitLab项目迁移全攻略:一键工具与API实践
  • SSD数据保持力失效:长期断电后数据为何会丢失?
  • Bad BPF项目深度解析:探索7个恶意eBPF程序的攻击原理与防御策略
  • ArcGIS栅格数据类型转换技巧与应用
  • 如何用DashPlayer实现英语学习革命:从被动观看到主动掌握的终极指南
  • SDC命令详解:使用相对路径访问设计对象(current_instance命令)
  • MySQL转SQLite的3步解决方案:免费在线工具完全指南
  • 光伏电站智能安防监控系统解决方案:全方位防护+高效运维
  • 大数据架构演进:挑战、解决方案与实战案例
  • 基于FPGA的Game Boy Color硬件复刻:从原理到实践的完整指南