首页 > 代码库 > Java如何转换protobuf-net中的bcl.DateTime对象

Java如何转换protobuf-net中的bcl.DateTime对象

一、定义DateTime Message

  参考文档:https://github.com/mgravell/protobuf-net/blob/master/src/Tools/bcl.proto

message DateTime
{
  optional sint64 value = 1; // the offset (in units of the selected scale) from 1970/01/01
  optional TimeSpanScale scale = 2 [default = DAYS]; // the scale of the timespan

  enum TimeSpanScale
  {
    DAYS = 0;
    HOURS = 1;
    MINUTES = 2;
    SECONDS = 3;
    MILLISECONDS = 4;
    TICKS = 5;

    MINMAX = 15; // dubious
  }
}

DateTime中包含两个属性:value,TimeSpanScale;
value为时间值,TimeSpanScale为时间模数:秒、微秒、毫微妙、Ticks;
Ticks是.net中的计时周期,参考:https://msdn.microsoft.com/zh-cn/library/system.datetime.ticks.aspx
1ticks=100毫微妙,10000ticks=1毫秒;

二、生成对应的Java类

protoc.exe -I=d:/tmp --java_out=d:/tmp d:/tmp/date_time.proto

三、解析C#DateTime为Java的java.util.Date

public class DateTimeUtil {

    private final static long TICKS_PER_MILLISECOND = 10000;

    /**
     * 将C#中的DateTime类型转为Java中的Date
     * 
     * @param bclDateTime
     * @return
     */
    public final static Date fromDateTimeToDate(DateTime dateTime) {
        long timeLong = dateTime.getValue();

        DateTime.TimeSpanScale timeSpanScale = dateTime.getScale();

        Calendar c = Calendar.getInstance();
        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

        switch (timeSpanScale) {
        case DAYS:
            // 24 * 60 * 60 * 1000
            c.setTimeInMillis(timeLong * 86400000);
            return c.getTime();
        case HOURS:
            // 60 * 60 * 1000
            c.setTimeInMillis(timeLong * 3600000);
            return c.getTime();
        case MINUTES:
            // 60 * 1000
            c.setTimeInMillis(timeLong * 60000);
            return c.getTime();
        case SECONDS:
            c.setTimeInMillis(timeLong * 1000);
            return c.getTime();
        case MILLISECONDS:
            c.setTimeInMillis(timeLong);
            return c.getTime();
        case TICKS:
            c.setTimeInMillis(timeLong / TICKS_PER_MILLISECOND);
            return c.getTime();
        default:
            c.setTimeInMillis(0L);

            return c.getTime();
        }
    }
}

 

参考文档:http://www.cnblogs.com/cuyt/p/6141723.html

 

Java如何转换protobuf-net中的bcl.DateTime对象