我在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()
然而,这只给我留下一个长表示毫秒。有没有更简单,更好的方法来得到时间?
当前回答
public static void main(String[] args) {
String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/14/2012 10:31:48";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
DateTime date11 = new DateTime(d1);
DateTime date22 = new DateTime(d2);
int days = Days.daysBetween(date11.withTimeAtStartOfDay(), date22.withTimeAtStartOfDay()).getDays();
int hours = Hours.hoursBetween(date11, date22).getHours() % 24;
int minutes = Minutes.minutesBetween(date11, date22).getMinutes() % 60;
int seconds = Seconds.secondsBetween(date11, date22).getSeconds() % 60;
if (hours > 0 || minutes > 0 || seconds > 0) {
days = days + 1;
}
System.out.println(days);
} catch (Exception e) {
e.printStackTrace();
}
}
这将为同一天提供日期差异
其他回答
如果你用d1和d2作为日期,最好的解决方案可能是这样的:
int days1 = d1.getTime()/(60*60*24*1000);//find the number of days since the epoch.
int days2 = d2.getTime()/(60*60*24*1000);
然后说
days2-days1
或者其他
不使用标准API,不行。你可以这样做:
class Duration {
private final TimeUnit unit;
private final long length;
// ...
}
或者你可以使用Joda:
DateTime a = ..., b = ...;
Duration d = new Duration(a, b);
我喜欢基于timeunit的方法,直到我发现它只覆盖了一个时间单元在下一个更高单位中有多少个单位是固定的这种微不足道的情况。当你想知道间隔了多少个月、多少年等时,这个问题就不成立了。
这里有一种计数方法,不像其他方法那么有效,但它似乎对我有用,而且还考虑到了夏令时。
public static String getOffsetAsString( Calendar cNow, Calendar cThen) {
Calendar cBefore;
Calendar cAfter;
if ( cNow.getTimeInMillis() < cThen.getTimeInMillis()) {
cBefore = ( Calendar) cNow.clone();
cAfter = cThen;
} else {
cBefore = ( Calendar) cThen.clone();
cAfter = cNow;
}
// compute diff
Map<Integer, Long> diffMap = new HashMap<Integer, Long>();
int[] calFields = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND};
for ( int i = 0; i < calFields.length; i++) {
int field = calFields[ i];
long d = computeDist( cAfter, cBefore, field);
diffMap.put( field, d);
}
final String result = String.format( "%dY %02dM %dT %02d:%02d:%02d.%03d",
diffMap.get( Calendar.YEAR), diffMap.get( Calendar.MONTH), diffMap.get( Calendar.DAY_OF_MONTH), diffMap.get( Calendar.HOUR_OF_DAY), diffMap.get( Calendar.MINUTE), diffMap.get( Calendar.SECOND), diffMap.get( Calendar.MILLISECOND));
return result;
}
private static int computeDist( Calendar cAfter, Calendar cBefore, int field) {
cBefore.setLenient( true);
System.out.print( "D " + new Date( cBefore.getTimeInMillis()) + " --- " + new Date( cAfter.getTimeInMillis()) + ": ");
int count = 0;
if ( cAfter.getTimeInMillis() > cBefore.getTimeInMillis()) {
int fVal = cBefore.get( field);
while ( cAfter.getTimeInMillis() >= cBefore.getTimeInMillis()) {
count++;
fVal = cBefore.get( field);
cBefore.set( field, fVal + 1);
System.out.print( count + "/" + ( fVal + 1) + ": " + new Date( cBefore.getTimeInMillis()) + " ] ");
}
int result = count - 1;
cBefore.set( field, fVal);
System.out.println( "" + result + " at: " + field + " cb = " + new Date( cBefore.getTimeInMillis()));
return result;
}
return 0;
}
在阅读了许多关于这个问题的回答和评论后,我的印象是,要么使用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);
}
这可能是最直接的方法了——也许是因为我已经用Java编写了一段时间了(它的日期和时间库确实很笨拙),但对我来说,代码看起来“简单而漂亮”!
您是否对以毫秒为单位返回的结果感到满意,或者您的问题的一部分是希望以某种替代格式返回?