获取自 Java 时代以来的天数、周数和月数java.time

2022-09-01 10:10:53

我试图在Java中获取自Epoch以来的天数,周数,月数。

Java Calendar类提供了诸如calendar.get(GregorianCalendar.DAY_OF_YEAR)或Calendary.get(GregorianCalendar.WEEK_OF_YEAR)之类的东西,这是一个良好的开端,但它并没有完全满足我的需求。

有没有一种优雅的方法可以在Java中做到这一点?


答案 1

您可以使用Joda Time库来轻松完成此操作 - 除了使用标准的Java Date和Calendar类之外,我将其用于任何与时间相关的内容。使用库查看以下示例:

MutableDateTime epoch = new MutableDateTime();
epoch.setDate(0); //Set to Epoch time
DateTime now = new DateTime();

Days days = Days.daysBetween(epoch, now);
Weeks weeks = Weeks.weeksBetween(epoch, now);
Months months = Months.monthsBetween(epoch, now);

System.out.println("Days Since Epoch: " + days.getDays());
System.out.println("Weeks Since Epoch: " + weeks.getWeeks());
System.out.println("Months Since Epoch: " + months.getMonths());

当我运行这个时,我得到以下输出:

Days Since Epoch: 15122
Weeks Since Epoch: 2160
Months Since Epoch: 496

答案 2

java.time

使用 Java 8 及更高版本中内置的 java.time 类。

LocalDate now = LocalDate.now();
LocalDate epoch = LocalDate.ofEpochDay(0);

System.out.println("Days: " + ChronoUnit.DAYS.between(epoch, now));
System.out.println("Weeks: " + ChronoUnit.WEEKS.between(epoch, now));
System.out.println("Months: " + ChronoUnit.MONTHS.between(epoch, now));

输出

Days: 16857
Weeks: 2408
Months: 553

推荐