自时期以来的时间和日期

问题描述 投票:0回答:1

我正在尝试编写一个仅打印当前日期的程序。所以我只需要年,月和日。我不允许使用任何日期,日历,公历或时间类别来获取当前日期。我能使用的只是System.currentTimeMillis()以获取自纪元以来的当前时间(以毫秒为单位),而java.util.TimeZone.getDefault()。getRawOffset()代表自纪元以来的时区。

到目前为止,我已经尝试将当前时间以毫秒为单位,除以1000得到秒,然后除以60得到分钟,然后得到60得到小时,依此类推。自从1970年1月1日起,我的工作日数降到18184。直到我将其完全除以30或31为止,因为并非所有月份都有30或31天,所以我不能简单地将其完全除。我找不到年份,因为leap年是365或364天。

class JulianDate {
    static void main() {
        long currentMilli = System.currentTimeMillis() + java.util.TimeZone.getDefault().getRawOffset();
        long seconds = currentMilli / 1000;
        long minutes = seconds / 60;
        long hours = minutes / 60;
        long days = hours / 24;
        System.out.println("Days since epoch : "  + days);
    }
}

我需要结束代码来简单地打印10/15/2019或2019年10月15日。格式无关紧要,我只需要它以纪元为单位打印当前的日,月和年]

java
1个回答
0
投票

这是给您的版本。它使用具有固定天数的4年区块,直到2100年为止。

public static void main(String[] args) {
    // Simple leap year counts, works until 2100
    int[] daysIn4Years = { 365, 365, 366, 365 }; // Starting 1970, 1971, 1972, 1973
    int daysIn4YearsTotal = IntStream.of(daysIn4Years).sum();
    int[][] daysInMonths = {
        { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
        { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }};
    int epochYear = 1970;
    long msIn1Day = 24 * 60 * 60 * 1000L;
    TimeZone timeZone = TimeZone.getDefault();

    long msSinceEpoch = System.currentTimeMillis() + timeZone.getRawOffset();
    int day = (int) (msSinceEpoch / msIn1Day);

    // Get the 4-year block
    int year = ((day / (daysIn4YearsTotal)) * 4) + epochYear;
    day %= daysIn4YearsTotal;

    // Adjust year within the block
    for (int daysInYear : daysIn4Years) {
        if (daysInYear > day) break;
        day -= daysInYear;
        year++;
    }
    boolean leapYear = year % 4 == 0; // simple leap year check < 2100

    // Iterate months
    int month = 0;
    for (int daysInMonth : daysInMonths[leapYear ? 1 : 0]) {
        if (daysInMonth > day) break;
        day -= daysInMonth;
        month++;
    }

    // day is 0..30, month is 0..11
    System.out.printf("%d/%d/%d", month + 1, day + 1, year);
}
© www.soinside.com 2019 - 2024. All rights reserved.