zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Spring5.2.x02日志体系
    【cdh6.3.2】阿里云盘
    日本产业大溃败:拥有无数世界第一,却被全世界抛弃
    Silverlight+WCF部署到IIS
    Silverlight部署常见问题
    html中调用js脚本是加入defer="defer" 作用
    ie6 ie7 ie8 ie9 ff css 区别
    jupyter notebook 安装nbextensions后不显示
    用flash导出动画时提示 “java运行时环境初始化时出现错误,您可能需要重新安装flash"
    Stylish 样式
  • 原文地址:https://www.cnblogs.com/liugh/p/6871531.html
Copyright © 2011-2022 走看看