問題描述
有沒有辦法將通過計算兩個日期之間的差異來計算的天數組織到不同的部分中,例如對于 364 天,它將是:0 年、11 個月、30 天、小時、分鐘等.我認為使用邏輯運算符可能像 % 和/一樣工作,但由于不同的月份有不同的天數,有些年份是閏年,我不知道該怎么做.任何幫助將非常感激.我的代碼:
is there a way of organising a number of days calculated by working out the difference between two dates, into different sections e.g. for 364 days it would be: 0 years, 11 months, 30 days, hours, minutes etc. I thought using logical operators may work like % and / but as different months have different amounts of days and some years are leap years i'm not sure how to do it. Any help would be much appreciated. My code:
import java.util.*;
public class CleanDate {
public static void main(String[] args) {
Calendar cDate = GregorianCalendar.getInstance();
cDate.set(2011, 0, 31, 00, 00, 00);
Date date1 = cDate.getTime();
Date date2 = new Date();
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.setTime(date1);
calendar2.setTime(date2);
long milliseconds1 = calendar1.getTimeInMillis();
long milliseconds2 = calendar2.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Time in minutes: " + diffMinutes + " minutes.");
System.out.println("Time in hours: " + diffHours + " hours.");
System.out.println("Time in days: " + diffDays + " days.");
}
}
推薦答案
你可以像這樣有效地使用 Joda Time:Interval
允許獲取兩個日期之間的時間間隔.
You could effectively use Joda Time like this:
Interval
allows to get time interval between two dates.
DateTime end = new DateTime(2006, 1, 1, 0, 0, 0, 0);
Interval interval = new Interval(start, end);
Period period = interval.toPeriod();
System.out.println(period.getYears()+" years, "
period.getMonths()+" months, "+period.getWeeks()+" weeks, "+period.getDays()+", days");
這篇關于將天數組織成年、月、日、小時的不同部分.爪哇的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!