简体   繁体   中英

Java equivalent for Python's toordinal()?

What is the best way to replicate datetime.datetime.now().toordinal() in java? I tried using epoch but the results are nowhere near.

There isn't any direct way to query that information using the Java Time API but you can calculate it.

public static void main(String[] args) {
    long ordinal = LocalDate.now().toEpochDay() + (146097 * 5L) - (31L * 365L + 7L);

    System.out.println(ordinal);
}

Run today, 19th April 2016, it outputs 736073 , which is consistent with Python's output.

From a LocalDate , you can get the Epoch day with toEpochDay() . If you take a look inside the current implementation , you'll find that it actually calculates the total number of days since year 0 and subtracts that with the constant

static final long DAYS_0000_TO_1970 = (DAYS_PER_CYCLE * 5L) - (30L * 365L + 7L);

where DAYS_PER_CYCLE = 146097 is the number of days in a 400 year cycle. That constant isn't public, so we can't reuse it directly.

From the Python documentation of toordinal() , it defines year 1 to have an ordinal of 1. The calculus above by the Java API supposes that it is year 0 instead so we just need to adjust for that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM