com.google.protobuf.Timestamp 轉 java.util.Date

在google.Timestamp的proto的文件中有詳細註釋以及原理。java

Timestamp的proto源代碼

message Timestamp {

  // Represents seconds of UTC time since Unix epoch
  // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
  // 9999-12-31T23:59:59Z inclusive.
  int64 seconds = 1;

  // Non-negative fractions of a second at nanosecond resolution. Negative
  // second values with fractions must still have non-negative nanos values
  // that count forward in time. Must be from 0 to 999,999,999
  // inclusive.
  int32 nanos = 2;
}

上述proto文件可知,timestamp定義兩個類型。google

一個是64位的整數類型: seconds 一個是32位的整數類型 : nanoscode

seconds的註釋中說明使用的是Unix時間戳,和Java的時間類型Date相對應。 因此只須要這個seconds數據便可完成轉換。get

/**
 * Create by guangxiaoLong on 2017-09-16
 */
public class ProtoUtil {


    static final long MILLIS_PER_SECOND = 1000;

    /**
     * google.proto.timestamp -> java.util.Date
     */
    public static Date timestampToDate(Timestamp timestamp) {
        return new Date(timestamp.getSeconds() * MILLIS_PER_SECOND);
    }

    /**
     * java.util.Date -> google.proto.timestamp
     */
    public static Timestamp dateTotimestamp(Date date) {
        return Timestamps.fromMillis(date.getTime());
    }
}
相關文章
相關標籤/搜索