Skip to content
Advertisement

C# DateTime.Ticks equivalent in Java

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

JavaScript

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

Advertisement

Answer

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

JavaScript

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:

JavaScript

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 🙁

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement