You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio用Java将系统日期时间转换为整数时间戳实现咨询

Android Java 系统时间转秒级整数时间戳实现方案

实现场景说明

你需要的1624029703属于10位秒级时间戳,Android Java 原生接口默认返回13位毫秒级时间戳,需要除以1000转换后即可得到目标格式。

方案1:直接获取当前系统时间的秒级整数时间戳

这是最简便的实现,无需额外日期解析:

// 优先用long类型存储,避免2038年溢出问题
long currentSecondTimestamp = System.currentTimeMillis() / 1000;

// 如需转为int类型,2038年之前的时间都可正常兼容
int currentIntTimestamp = (int) (System.currentTimeMillis() / 1000);

方案2:指定格式的日期字符串转秒级整数时间戳

可兼容2021-06-18 19:51:43这类自定义格式的日期转换,适配所有Android版本:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

// 按你需要的日期格式构造解析器,指定中国时区保证和示例结果一致
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
try {
    String inputTime = "2021-06-18 19:51:43";
    Date date = sdf.parse(inputTime);
    if (date != null) {
        // 转换为秒级时间戳
        long secondTimestamp = date.getTime() / 1000;
        int targetIntTimestamp = (int) secondTimestamp;
        // 此处targetIntTimestamp的值就是1624029703,和示例完全匹配
    }
} catch (ParseException e) {
    // 日期格式不匹配时的异常处理逻辑
    e.printStackTrace();
}

方案3:Android 8.0(API 26+)更安全的实现

使用官方推荐的java.time包,避免SimpleDateFormat的线程安全问题:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

// 构造日期格式化器
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 解析日期字符串
LocalDateTime dateTime = LocalDateTime.parse("2021-06-18 19:51:43", formatter);
// 转换为东八区秒级时间戳
long secondTimestamp = dateTime.atZone(ZoneId.of("Asia/Shanghai")).toEpochSecond();
int targetIntTimestamp = (int) secondTimestamp;

注意事项

  • 构造日期解析器时必须指定时区,否则不同地区设备默认时区不同会导致转换结果偏差
  • 32位int类型的最大值为2147483647,对应北京时间2038-01-19 11:14:07,超过该时间的秒级时间戳无法用int存储,业务兼容2038年之后的时间建议优先用long类型存储

内容的提问来源于stack exchange,提问作者Dr.NINJS

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 02:18:01