問題描述
我試圖在 Java 中獲取自 Epoch 以來的天數、周數、月數.
I'm trying to get the number of days, weeks, months since Epoch in Java.
Java Calendar 類提供了諸如 calendar.get(GregorianCalendar.DAY_OF_YEAR) 或 Calendar.get(GregorianCalendar.WEEK_OF_YEAR) 之類的東西,這是一個好的開始,但它并不能完全滿足我的需要.
The Java Calendar class offers things like calendar.get(GregorianCalendar.DAY_OF_YEAR), or Calendar.get(GregorianCalendar.WEEK_OF_YEAR), which is a good start but it doesn't do exactly what I need.
在 Java 中是否有一種優雅的方法可以做到這一點?
Is there an elegant way to do this in Java?
推薦答案
你可以使用 Joda Timelibrary 很容易做到這一點 - 除了使用標準 Java Date 和 Calendar 類之外,我將它用于與時間相關的任何事情.看看下面使用該庫的示例:
You can use the Joda Time library to do this pretty easily - I use it for anything time related other than using the standard Java Date and Calendar classes. Take a look at the example below using the library:
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());
當我運行它時,我得到以下輸出:
When I run this I get the following output:
Days Since Epoch: 15122
Weeks Since Epoch: 2160
Months Since Epoch: 496
這篇關于獲取自 Java 中的 Epoch 以來的天數、周數和月數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!