【问题标题】:Time and Date since epoch自纪元以来的时间和日期
【发布时间】:2019-10-16 03:27:27
【问题描述】:

我正在尝试编写一个仅打印当前日期的程序。所以我只需要年、月和日。我不允许使用任何日期、日历、公历或时间类来获取当前日期。我只能使用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。格式无关紧要,我只需要它根据纪元毫秒打印当前日期、月份和年份

【问题讨论】:

  • 你认为你可能会倒退吗?您可以在谷歌上找到一个公式来确定闰年。然后酌情以 365 或 366 块计算 1970 年 1 月 1 日之后的年份。然后,当您的剩余天数少于一年时,以当月的实际天数计算月份。你总是从 1 月 1 日开始工作,所以你知道你正在处理的月份,以及它是否是闰年。然后,当您的时间少于 30 天且不是 2 月时,开始计算各个天数。
  • 您可能有兴趣阅读此主题:stackoverflow.com/questions/1021324/…

标签: java


【解决方案1】:

这是适合您的版本。这使用具有恒定天数的 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);
}

【讨论】:

    猜你喜欢
    • 2010-11-24
    • 2016-04-17
    • 2013-11-02
    • 2012-08-05
    • 2012-01-31
    • 2017-07-23
    • 2011-07-04
    • 2011-08-31
    • 2013-03-26
    相关资源
    最近更新 更多