获取的日,周或数月数,因为时代在Java中获取的日,周或数月数,因为时代在Java中(Get the

2019-05-12 00:06发布

我试图让纪元以来的Java的日,周,月数。

Java的Calendar类提供的东西像calendar.get(GregorianCalendar.DAY_OF_YEAR),或Calendar.get(GregorianCalendar.WEEK_OF_YEAR),这是一个良好的开端,但它不这样做正是我需要的。

有一种优雅的方式在Java中做到这一点?

Answer 1:

您可以使用约达时间库要做到这一点很容易地-我用它比使用标准的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


Answer 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


Answer 3:

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));


Answer 4:

我有点诧异间,几乎所有的答案是实际计算天epochnow 。 随着java.time.LocalDate它的那样简单:

LocalDate.now().toEpochDay()


Answer 5:

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

您可以使用此和多少毫秒的间隔知识,你在乎做计算。



Answer 6:

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);


Answer 7:

我不认为会有这样做的一种优雅的方式,因为它不是一个很常见的要求。 我不禁想知道为什么要这么做?

但无论如何,我会做的方式是从减去时代日期Calendar ,然后得到你想要的字段:

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

int yearsSinceEpoch = timeSinceEpoch.get(Calendar.YEAR);
int monthsSinceEpoch = timeSinceEpoch.get(Calendar.MONTH) + 12 * yearsSinceEpoch;


文章来源: Get the number of days, weeks, and months, since Epoch in Java