31

我正在尝试获取自 Java Epoch 以来的天数、周数、月数。

Java Calendar 类提供了诸如calendar.get(GregorianCalendar.DAY_OF_YEAR) 或Calendar.get(GregorianCalendar.WEEK_OF_YEAR) 之类的东西,这是一个好的开始,但它并不能完全满足我的需要。

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

4

7 回答 7

35

您可以使用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
于 2011-05-27T22:18:25.943 回答
30

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
于 2016-02-26T08:43:08.650 回答
15

我有点惊讶,几乎所有答案实际上都是在计算 和 之间的天epochnow。使用java.time.LocalDate它很简单:

LocalDate.now().toEpochDay()
于 2018-11-14T15:51:07.893 回答
10
Long currentMilli = System.currentTimeMillis();
Long seconds = currentMilli / 1000;
Long minutes = seconds / 60;
Long hours = minutes / 60;
Long days = hours / 24;
System.out.println("Days since epoch : "  + days);

或者

System.out.println("Days since epoch : "  + ((int) currentMilli / 86400000));
于 2012-09-27T04:32:20.190 回答
1
Calendar now = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0); // start at EPOCH

int days = 0
while (cal.getTimeInMillis() < now.getTimeInMillis()) {
  days += 1
  cal.add(Calendar.DAY_OF_MONTH, 1) // increment one day at a time
}
System.out.println("Days since EPOCH = " + days);
于 2011-05-27T21:59:49.597 回答
0

我不希望有一种优雅的方式来做到这一点,因为这不是一个非常普遍的要求。我不禁想知道你为什么要这样做...

但无论如何,我这样做的方法是从 中减去纪元日期Calendar,然后得到你想要的字段:

Calendar timeSinceEpoch = Calendar.getInstance();
timeSinceEpoch.add(Calendar.YEAR, -1970);

int yearsSinceEpoch = timeSinceEpoch.get(Calendar.YEAR);
int monthsSinceEpoch = timeSinceEpoch.get(Calendar.MONTH) + 12 * yearsSinceEpoch;
于 2011-05-27T22:03:37.257 回答
-3

Date.getTime()- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。

您可以使用它并了解您关心的间隔中有多少毫秒来进行计算。

于 2011-05-27T21:57:05.267 回答