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; }
        }
    

你可能感兴趣的:(java,工具使用,java)