C#DateTime.Ticks相当于在Java中 [英] C# DateTime.Ticks equivalent in Java

查看:2284
本文介绍了C#DateTime.Ticks相当于在Java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是Java相当于DateTime.Ticks在C#?

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);

会有什么上面提到的code相当于在Java中?

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

推荐答案

好了,java.util.Date/Calendar只有precision精确到毫秒:

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

这是最近的有效当量。如果你需要一个.NET蜱值和日期间进行转换 / 日历您基本上需要执行缩放(蜱到米利斯)和抵消(1月1日至1AD 1970年1月)。

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的内置日期和时间的API是相当不愉快。我个人建议您使用乔达时间的替代。如果你能说你真正想要做什么,我们可以帮助更多。

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.

编辑:好的,这里的一些样品code:

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);
    }
}

请注意,此构造一个日期/日历再presenting的2019年9月14日的 UTC 的瞬间。在.NET重新presentation是有点模糊 - 您可以创建这是除了他们的厚道相同的两个日期时间值(但因此重新present不同时刻),他们会声称自己是平等的。这是一个有点乱:(

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 :(

这篇关于C#DateTime.Ticks相当于在Java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆