java ticks,C#DateTime.Ticks相当于在Java中

What is the Java equivalent of DateTime.Ticks in C#?

DateTime dt = new DateTime(2010, 9, 14, 0, 0, 0);

Console.WriteLine("Ticks: {0}", dt.Ticks);

What will be the equivalent of above mentioned code in Java?

解决方案

Well, java.util.Date/Calendar only have precision down to the millisecond:

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MILLISECOND, 0); // Clear the millis part. Silly API.

calendar.set(2010, 8, 14, 0, 0, 0); // Note that months are 0-based

Date date = calendar.getTime();

long millis = date.getTime(); // Millis since Unix epoch

That's the nearest effective equivalent. If you need to convert between a .NET ticks value and a Date/Calendar you basically need to perform scaling (ticks to millis) and offsetting (1st Jan 1AD to 1st Jan 1970).

Java's built-in date and time APIs are fairly unpleasant. I'd personally recommend that you use Joda Time instead. If you could say what you're really trying to do, we can help more.

EDIT: Okay, here's some sample code:

import java.util.*;

public class Test {

private static final long TICKS_AT_EPOCH = 621355968000000000L;

private static final long TICKS_PER_MILLISECOND = 10000;

public static void main(String[] args) {

long ticks = 634200192000000000L;

Date date = new Date((ticks - TICKS_AT_EPOCH) / TICKS_PER_MILLISECOND);

System.out.println(date);

TimeZone utc = TimeZone.getTimeZone("UTC");

Calendar calendar = Calendar.getInstance(utc);

calendar.setTime(date);

System.out.println(calendar);

}

}

Note that this constructs a Date/Calendar representing the UTC instant of 2019/9/14. The .NET representation is somewhat fuzzy - you can create two DateTime values which are the same except for their "kind" (but therefore represent different instants) and they'll claim to be equal. It's a bit of a mess :(

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值