View Javadoc
1   /*
2    * Copyright 2021 TiKV Project Authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   *
16   */
17  
18  package org.tikv.common;
19  
20  import java.sql.Timestamp;
21  import org.joda.time.DateTime;
22  
23  /** Extend joda DateTime to support micro second */
24  public class ExtendedDateTime {
25  
26    private final DateTime dateTime;
27    private final int microsOfMillis;
28  
29    /**
30     * if timestamp = 2019-11-11 11:11:11 123456, then dateTime = 2019-11-11 11:11:11 123
31     * microInMillis = 456
32     *
33     * @param dateTime
34     * @param microsOfMillis
35     */
36    public ExtendedDateTime(DateTime dateTime, int microsOfMillis) {
37      this.dateTime = dateTime;
38      this.microsOfMillis = microsOfMillis;
39    }
40  
41    public ExtendedDateTime(DateTime dateTime) {
42      this.dateTime = dateTime;
43      this.microsOfMillis = 0;
44    }
45  
46    public DateTime getDateTime() {
47      return dateTime;
48    }
49  
50    public int getMicrosOfSeconds() {
51      return dateTime.getMillisOfSecond() * 1000 + microsOfMillis;
52    }
53  
54    public int getMicrosOfMillis() {
55      return microsOfMillis;
56    }
57  
58    public Timestamp toTimeStamp() {
59      Timestamp timestamp = new Timestamp(dateTime.getMillis() / 1000 * 1000);
60      timestamp.setNanos(dateTime.getMillisOfSecond() * 1000000 + microsOfMillis * 1000);
61      return timestamp;
62    }
63  
64    public long toEpochMicro() {
65      return toTimeStamp().getTime() * 1000 + getMicrosOfMillis();
66    }
67  }