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());
    }
}
相关文章
相关标签/搜索