
正文
Java如何转换protobuf-net中的bcl.DateTime对象
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、定义DateTime Message
参考文档:https://github.com/mgravell/protobuf-net/blob/master/src/Tools/bcl.proto
message DateTime
{
optional sint64 value = ; // the offset (in units of the selected scale) from 1970/01/01
optional TimeSpanScale scale = [default = DAYS]; // the scale of the timespan enum TimeSpanScale
{
DAYS = ;
HOURS = ;
MINUTES = ;
SECONDS = ;
MILLISECONDS = ;
TICKS = ; MINMAX = ; // 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 = ;
/**
* 将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 * );
return c.getTime();
case HOURS:
// 60 * 60 * 1000
c.setTimeInMillis(timeLong * );
return c.getTime();
case MINUTES:
// 60 * 1000
c.setTimeInMillis(timeLong * );
return c.getTime();
case SECONDS:
c.setTimeInMillis(timeLong * );
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







