java - 自纪元以来的时间和日期
问题描述
我正在尝试编写一个仅打印当前日期的程序。所以我只需要年、月和日。我不允许使用任何日期、日历、公历或时间类来获取当前日期。我所能使用的只是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/2019
或October 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);
}
推荐阅读
- sql - SQL中的函数会给我一个独特的int?
- c# - Unity3D sqlite多个“System.Data.dll”问题
- python - 如何修复 Traceback 到旧代码版本?
- c# - 使用存储库模式 LINQ 查询的登录页面。出现错误
- python - 带有负反馈的 TensorFlow 优化器?
- python - 在 python 3 中不使用 OpenCV 旋转图像
- c# - Unity3D:Mixamo 动画存在问题,动画有效,但角色图形改变了它们的位置
- c# - 仅在服务器端使用证书
- ruby-on-rails - 如何使用 CSV 的标头作为请求标头在我的 API 中上传 CSV 文件的内容
- json - 如何在没有任何功能的情况下将另一个对象中的 JSON 对象转换为字符串