Skip to content
Advertisement

C# DateTime.Ticks equivalent in 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?

Advertisement

Answer

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 🙁

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