我正在尝试获取自Java时代以来的天数,周数,月数。
Java Calendar类提供了诸如calendar.get(GregorianCalendar.DAY_OF_YEAR)或Calendar.get(GregorianCalendar.WEEK_OF_YEAR)之类的东西,这是一个不错的开始,但它并不能完全满足我的需求。
在Java中是否有一种优雅的方法来做到这一点?
最佳答案
您可以使用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
关于java - 获取自Java中的Epoch以来的天数,周数和月数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6158053/