繁体   English   中英

自纪元以来的时间和日期

[英]Time and Date since epoch

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

到目前为止,我所尝试的是以毫秒为单位的当前时间除以 1000 得到秒,然后 60 得到分钟,然后 60 得到小时,依此类推。 这工作正常,直到我从 1970 年 1 月 1 日开始算起 18184 天。我不能简单地将这些天完全除以 30 或 31,因为并非所有月份都有 30 或 31 天。 我也找不到年份,因为闰年是 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/2019October 15, 2019 格式无关紧要,我只需要它根据纪元毫秒打印当前日期、月份和年份

这是给你的一个版本。 这使用具有恒定天数的 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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