Timestamp

发布时间 2023-12-21 10:20:22作者: anpeiyong

概述

A thin wrapper around <code>java.util.Date</code> that allows the JDBC API to identify this as an SQL <code>TIMESTAMP</code> value.
It adds the ability to hold the SQL <code>TIMESTAMP</code> fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds.
A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.

Timestamp是java.util.Date的wrapper,允许JDBC API识别作为一个SQL的时间戳值;

Timestamp提供了持有纳秒值的能力;

 

This type is a composite of a <code>java.util.Date</code> and a separate nanoseconds value.
Only integral seconds are stored in the <code>java.util.Date</code> component.
The fractional seconds - the nanos - are separate.
The <code>Timestamp.equals(Object)</code> method never returns <code>true</code> when passed an object that isn't an instance of <code>java.sql.Timestamp</code>, because the nanos component of a date is unknown.
As a result, the <code>Timestamp.equals(Object)</code> method is not symmetric with respect to the <code>java.util.Date.equals(Object)</code> method.
Also, the <code>hashCode</code> method uses the underlying <code>java.util.Date</code> implementation and therefore does not include nanos in its computation.

Timestamp是Date和纳秒值的组合

整数秒 存在Date中,纳秒是分离的;

Timestamp.equals(Object)时,如果参数不是Timestamp的实例,永远不会返回true,因为没有纳秒值;

hashcode方法使用的是Date的,不包含纳秒;

 

 

public class Timestamp extends java.util.Date {

        private int nanos;
        
        public Timestamp(long time) {
            super((time/1000)*1000);
            nanos = (int)((time%1000) * 1000000);
            if (nanos < 0) {
                nanos = 1000000000 + nanos;
                super.setTime(((time/1000)-1)*1000);
            }
        }

        // Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this <code>Timestamp</code> object.
        public long getTime() {
            long time = super.getTime();
            return (time + (nanos / 1000000));
        }

        // Gets this <code>Timestamp</code> object's <code>nanos</code> value.
        public int getNanos() {
            return nanos;
        }
    }