java如何将时间戳转为秒

如何将时间戳转为秒
通常的做法
public static long toSecondMethod1(long timestamp) {
    return timestamp / 1000;
}
直接使用TimeUnit工具箱中的方法

一个更友好点的方法

 public static long toSecondMethod2(long timestamp) {
    return TimeUnit.MILLISECONDS.toSeconds(timestamp);
 }
测试代码
 public static void main(String[] args) {
        long timestamp = System.currentTimeMillis();
        long method1 = toSecondMethod1(timestamp);
        long method2= toSecondMethod2(timestamp);
        System.out.println("timestamp:" + timestamp);
        System.out.println("method1:" + method1);
        System.out.println("method2:" + method2);
 }
输出结果
timestamp:1618100030482
method1:1618100030
method2:1618100030

可以看到结果是一样,我们可以进入TimeUnit(java.util.concurrent)中,看一下具体的实现


    /**
     * Time unit representing one thousandth of a second
     */
    MILLISECONDS {
        public long toNanos(long d)   { return x(d, C2/C0, MAX/(C2/C0)); }
        public long toMicros(long d)  { return x(d, C2/C1, MAX/(C2/C1)); }
        public long toMillis(long d)  { return d; }
        public long toSeconds(long d) { return d/(C3/C2); }
        public long toMinutes(long d) { return d/(C4/C2); }
        public long toHours(long d)   { return d/(C5/C2); }
        public long toDays(long d)    { return d/(C6/C2); }
        public long convert(long d, TimeUnit u) { return u.toMillis(d); }
        int excessNanos(long d, long m) { return 0; }
    },


 // Handy constants for conversion methods
    static final long C0 = 1L;
    static final long C1 = C0 * 1000L;
    static final long C2 = C1 * 1000L;
    static final long C3 = C2 * 1000L;
    static final long C4 = C3 * 60L;
    static final long C5 = C4 * 60L;
    static final long C6 = C5 * 24L;

通过以上的两段代码,可以看出,内部实现和我们的实现一样的。

使用TimeUnit有什么好处呢?
  1. 如果我们除了将时间戳转为秒的需求,还可能将时间戳转为小时,转为分钟等,那该工具箱提供了toHours等方法使用。

  2. 如果我们的源头不止时间戳,可能是将秒转为小时等,同样的也会有TimeUnit.SECONDS对应的方法使用。

      SECONDS {
            public long toNanos(long d)   { return x(d, C3/C0, MAX/(C3/C0)); }
            public long toMicros(long d)  { return x(d, C3/C1, MAX/(C3/C1)); }
            public long toMillis(long d)  { return x(d, C3/C2, MAX/(C3/C2)); }
            public long toSeconds(long d) { return d; }
            public long toMinutes(long d) { return d/(C4/C3); }
            public long toHours(long d)   { return d/(C5/C3); }
            public long toDays(long d)    { return d/(C6/C3); }
            public long convert(long d, TimeUnit u) { return u.toSeconds(d); }
            int excessNanos(long d, long m) { return 0; }
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

51iwowo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值