200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > java的Date.getTime()转换成C#的Datetime.ticks

java的Date.getTime()转换成C#的Datetime.ticks

时间:2021-12-20 05:44:26

相关推荐

java的Date.getTime()转换成C#的Datetime.ticks

先来个名词解释:

Epoch time:指从1970年1月1日零时起到现在为止的"second(秒) 数".

注意我给"second(秒) 数"加了引号,是因为在不一样的项目中,计量单位可能是不同的,需要仔细的阅读相关文档.比如Gtalk Api的Gmail Notifications文档中,所使用的date数为从1970年1月1日零时起到现在为止的"millisecond(毫秒) 数".

C#的Datetime.ticks:指从0001年1月1日零时起到现在为止的one ten-millionth of a second数量,或者one hundred nanoseconds of a second数量,也就是"千万分之一秒"的数量.

java的Date.getTime():这个方法返回目标时间到1970年1月1日零时为止的"millisecond(毫秒) 数".

然后来做个转换:

1 second(秒)=1000 millisecond(毫秒)=10 x 100 0000 one ten-millionth of a second(千万分之一秒)

好了,接下来是我们的java转换函数

public static long GetTicks(String epochStr)

{

//convert the target-epoch time to a well-format string

String date = new java.text.SimpleDateFormat("yyyy/MM/dd/HH/mm/ss").format(new Date (Long.parseLong(epochStr)));

String[] ds=date.split("/");

//start of the ticks time

Calendar calStart=Calendar.getInstance();

calStart.set(1, 1, 3, 0, 0, 0);

//the target time

Calendar calEnd=Calendar.getInstance();

calEnd.set(Integer.parseInt(ds[0]) ,Integer.parseInt(ds[1]),Integer.parseInt(ds[2]),Integer.parseInt(ds[3]),Integer.parseInt(ds[4]),Integer.parseInt(ds[5]) );

//epoch time of the ticks-start time

long epochStart=calStart.getTime().getTime();

//epoch time of the target time

long epochEnd=calEnd.getTime().getTime();

//get the sum of epoch time, from the target time to the ticks-start time

long all=epochEnd-epochStart;

//convert epoch time to ticks time

long ticks=( (all/1000) * 1000000) * 10;

return ticks;

}

用图来说明:

| | |

目标时间 1970年 0001年

我是分别取得目标时间和0001年到1970年的"millisecond(毫秒) 数",然后加在一起,这样就得到了目标时间到0001年的"millisecond(毫秒) 数",然后把这个数字换算成"千万分之一秒"的数量,得到ticks数.

或许你会发现,为什么0001年的计算从1月3号起,不是应该1月1号吗.这个问题我也很奇怪,因为我发现如果从1月1号起,时间上就总是差着两天,这原因等待高手来解决 :)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。