我试图获得自Java中Epoch以来的天数,周数,月数。
Java Calendar类提供了诸如calendar.get(GregorianCalendar.DAY_OF_YEAR)或Calendar.get(GregorianCalendar.WEEK_OF_YEAR)之类的东西,这是一个很好的开始,但它并不能完全满足我的需要。
在Java中有优雅的方法吗?
答案 0 :(得分:35)
您可以使用Joda Time library非常轻松地执行此操作 - 除了使用标准的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
答案 1 :(得分:20)
使用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
答案 2 :(得分:9)
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));
答案 3 :(得分:1)
令我惊讶的是,几乎所有答案实际上都在计算<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XF_Login.Pages.RegisterPage" >
至epoch
之间的天数。使用now
的过程非常简单:
java.time.LocalDate
答案 4 :(得分:0)
Date.getTime()
- 返回自此Date对象表示的1970年1月1日00:00:00 GMT以来的毫秒数。
您可以使用此功能,并了解您关心计算间隔中的毫秒数。
答案 5 :(得分:0)
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);
答案 6 :(得分: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;