View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *     http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shardingsphere.db.protocol.mysql.packet.binlog.row.column.value.time;
19  
20  import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.row.column.MySQLBinlogColumnDef;
21  import org.apache.shardingsphere.db.protocol.mysql.packet.binlog.row.column.value.MySQLBinlogProtocolValue;
22  import org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload;
23  
24  import java.io.Serializable;
25  import java.sql.Timestamp;
26  import java.time.LocalDateTime;
27  import java.util.Date;
28  
29  /**
30   * MySQL DATETIME binlog protocol value.
31   * Stored value is in the format YYYYMMDDHHMMSS and can be easily extracted by repeatedly calculating the remainder of dividing the value by 100 and dividing the value by 100
32   *
33   * @see <a href="https://dev.mysql.com/doc/dev/mysql-server/latest/field__types_8h.html">field type</a>
34   */
35  public final class MySQLDatetimeBinlogProtocolValue implements MySQLBinlogProtocolValue {
36      
37      @Override
38      public Serializable read(final MySQLBinlogColumnDef columnDef, final MySQLPacketPayload payload) {
39          long datetime = payload.readInt8();
40          return 0 == datetime ? MySQLTimeValueUtils.DATETIME_OF_ZERO : readDateTime(datetime);
41      }
42      
43      private Date readDateTime(final long datetime) {
44          int date = (int) (datetime / 1000000);
45          int year = date / 10000;
46          int month = (date % 10000) / 100;
47          int day = date % 100;
48          int time = (int) (datetime % 1000000);
49          int hour = time / 10000;
50          int minute = (time % 10000) / 100;
51          int second = time % 100;
52          return Timestamp.valueOf(LocalDateTime.of(year, month, day, hour, minute, second));
53      }
54  }