我在Scala中使用Java的Java .util.Date类,并希望比较Date对象和当前时间。我知道我可以通过使用getTime()来计算delta:
(new java.util.Date()).getTime() - oldDate.getTime()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
我在Scala中使用Java的Java .util.Date类,并希望比较Date对象和当前时间。我知道我可以通过使用getTime()来计算delta:
(new java.util.Date()).getTime() - oldDate.getTime()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
当前回答
在阅读了许多关于这个问题的回答和评论后,我的印象是,要么使用Joda时间,要么考虑到日光节约时间的一些特点等等。由于这两种方法我都不想做,所以我最终编写了几行代码来计算两个日期之间的差异,而没有使用任何与日期或时间相关的Java类。
在下面的代码中,年、月和日的数字与现实生活中的数字相同。例如,2015年12月24日,年= 2015,月= 12,日= 24。
我想分享这些代码,以防其他人想要使用它。有3种方法:1)找出给定年份是否是闰年的方法2)计算给定年份1月1日的天数的方法3)计算任意两个日期之间天数的方法2(结束日期减去开始日期)。
方法如下:
1)
public static boolean isLeapYear (int year) {
//Every 4. year is a leap year, except if the year is divisible by 100 and not by 400
//For example 1900 is not a leap year but 2000 is
boolean result = false;
if (year % 4 == 0) {
result = true;
}
if (year % 100 == 0) {
result = false;
}
if (year % 400 == 0) {
result = true;
}
return result;
}
2)
public static int daysGoneSince (int yearZero, int year, int month, int day) {
//Calculates the day number of the given date; day 1 = January 1st in the yearZero
//Validate the input
if (year < yearZero || month < 1 || month > 12 || day < 1 || day > 31) {
//Throw an exception
throw new IllegalArgumentException("Too many or too few days in month or months in year or the year is smaller than year zero");
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {//Months with 30 days
if (day == 31) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
else if (month == 2) {//February 28 or 29
if (isLeapYear(year)) {
if (day > 29) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
else if (day > 28) {
//Throw an exception
throw new IllegalArgumentException("Too many days in month");
}
}
//Start counting days
int days = 0;
//Days in the target month until the target day
days = days + day;
//Days in the earlier months in the target year
for (int i = 1; i < month; i++) {
switch (i) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
days = days + 31;
break;
case 2:
days = days + 28;
if (isLeapYear(year)) {
days = days + 1;
}
break;
case 4: case 6: case 9: case 11:
days = days + 30;
break;
}
}
//Days in the earlier years
for (int i = yearZero; i < year; i++) {
days = days + 365;
if (isLeapYear(i)) {
days = days + 1;
}
}
return days;
}
3)
public static int dateDiff (int startYear, int startMonth, int startDay, int endYear, int endMonth, int endDay) {
int yearZero;
//daysGoneSince presupposes that the first argument be smaller or equal to the second argument
if (10000 * startYear + 100 * startMonth + startDay > 10000 * endYear + 100 * endMonth + endDay) {//If the end date is earlier than the start date
yearZero = endYear;
}
else {
yearZero = startYear;
}
return daysGoneSince(yearZero, endYear, endMonth, endDay) - daysGoneSince(yearZero, startYear, startMonth, startDay);
}
其他回答
有很多方法可以找到日期和时间之间的区别。我所知道的最简单的方法之一是:
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
calendar1.set(2012, 04, 02);
calendar2.set(2012, 04, 04);
long milsecs1= calendar1.getTimeInMillis();
long milsecs2 = calendar2.getTimeInMillis();
long diff = milsecs2 - milsecs1;
long dsecs = diff / 1000;
long dminutes = diff / (60 * 1000);
long dhours = diff / (60 * 60 * 1000);
long ddays = diff / (24 * 60 * 60 * 1000);
System.out.println("Your Day Difference="+ddays);
打印语句只是一个示例—您可以按照自己喜欢的方式格式化它。
看看Joda Time,它是一个改进的Java日期/时间API,应该可以很好地与Scala一起工作。
这是一个正确的Java 7解决方案,没有任何依赖。
public static int countDaysBetween(Date date1, Date date2) {
Calendar c1 = removeTime(from(date1));
Calendar c2 = removeTime(from(date2));
if (c1.get(YEAR) == c2.get(YEAR)) {
return Math.abs(c1.get(DAY_OF_YEAR) - c2.get(DAY_OF_YEAR)) + 1;
}
// ensure c1 <= c2
if (c1.get(YEAR) > c2.get(YEAR)) {
Calendar c = c1;
c1 = c2;
c2 = c;
}
int y1 = c1.get(YEAR);
int y2 = c2.get(YEAR);
int d1 = c1.get(DAY_OF_YEAR);
int d2 = c2.get(DAY_OF_YEAR);
return d2 + ((y2 - y1) * 365) - d1 + countLeapYearsBetween(y1, y2) + 1;
}
private static int countLeapYearsBetween(int y1, int y2) {
if (y1 < 1 || y2 < 1) {
throw new IllegalArgumentException("Year must be > 0.");
}
// ensure y1 <= y2
if (y1 > y2) {
int i = y1;
y1 = y2;
y2 = i;
}
int diff = 0;
int firstDivisibleBy4 = y1;
if (firstDivisibleBy4 % 4 != 0) {
firstDivisibleBy4 += 4 - (y1 % 4);
}
diff = y2 - firstDivisibleBy4 - 1;
int divisibleBy4 = diff < 0 ? 0 : diff / 4 + 1;
int firstDivisibleBy100 = y1;
if (firstDivisibleBy100 % 100 != 0) {
firstDivisibleBy100 += 100 - (firstDivisibleBy100 % 100);
}
diff = y2 - firstDivisibleBy100 - 1;
int divisibleBy100 = diff < 0 ? 0 : diff / 100 + 1;
int firstDivisibleBy400 = y1;
if (firstDivisibleBy400 % 400 != 0) {
firstDivisibleBy400 += 400 - (y1 % 400);
}
diff = y2 - firstDivisibleBy400 - 1;
int divisibleBy400 = diff < 0 ? 0 : diff / 400 + 1;
return divisibleBy4 - divisibleBy100 + divisibleBy400;
}
public static Calendar from(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}
public static Calendar removeTime(Calendar c) {
c.set(HOUR_OF_DAY, 0);
c.set(MINUTE, 0);
c.set(SECOND, 0);
c.set(MILLISECOND, 0);
return c;
}
如果你想修复跨越夏时制边界的日期范围的问题(例如,一个日期在夏季,另一个日期在冬季),你可以使用这个来获得天数的差异:
public static long calculateDifferenceInDays(Date start, Date end, Locale locale) {
Calendar cal = Calendar.getInstance(locale);
cal.setTime(start);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long startTime = cal.getTimeInMillis();
cal.setTime(end);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long endTime = cal.getTimeInMillis();
// calculate the offset if one of the dates is in summer time and the other one in winter time
TimeZone timezone = cal.getTimeZone();
int offsetStart = timezone.getOffset(startTime);
int offsetEnd = timezone.getOffset(endTime);
int offset = offsetEnd - offsetStart;
return TimeUnit.MILLISECONDS.toDays(endTime - startTime + offset);
}
只需在两个Date对象上使用下面的方法。如果你想传递当前日期,只需传递new date()作为第二个参数,因为它是用当前时间初始化的。
public String getDateDiffString(Date dateOne, Date dateTwo)
{
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return "dateTwo is " + delta + " days after dateOne";
}
else {
delta *= -1;
return "dateTwo is " + delta + " days before dateOne";
}
}
此外,除了从天数,如果,你也想要其他参数的差异,使用下面的片段,
int year = delta / 365;
int rest = delta % 365;
int month = rest / 30;
rest = rest % 30;
int weeks = rest / 7;
int days = rest % 7;
p.s. Code完全取自SO答案。