Java以这种格式减去两个日期 [英] Java subtract two dates in this format

查看:64
本文介绍了Java以这种格式减去两个日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

计算Java中日期的差异

你如何减去Java中的日期?

I我正在解析一个字符串中的两个日期:

I am parsing two dates from a string that look like:

Oct 15, 2012 1:07:13 PM
Oct 23, 2012 03:43:34 PM

我需要做的是找出这两者之间的区别date,ex:

What I need to do is find the difference between these two dates, ex:

Oct 23, 2012 03:43:34 PM - Oct 15, 2012 1:07:13 PM

= 8天2小时36分21秒

= 8 days 2 hours 36 minutes 21 seconds

^这是我需要得到的两个日期/时间

^ This is what I need to get with the two date/times I have

我相信我需要解析格式并将其转换为另一种格式,然后减去和之间的区别数学得到日/小时/分钟/秒之间

I believe I need to parse the format and convert it to another format, then subtract the difference between and do the math to get the days/hours/minutes/seconds between

推荐答案

与其他回答者试图暗示的相反,计算差异两个日期之间的标准Java SE并不是那么简单。

In contrary to what other answerers try to imply, calculating the difference between two dates isn't that trivial in standard Java SE.

你的第一步确实是将这些字符串转换为可用的日期实例。您可以使用 SimpleDateFormat执行此操作 。这是一个启动示例:

Your first step is indeed to convert those strings to useable Date instances. You can do this using SimpleDateFormat. Here's a kickoff example:

String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";

SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:mm:ss a", Locale.ENGLISH);

Date date1 = sdf.parse(string1);
Date date2 = sdf.parse(string2);

(请注意可选<$​​ c $ c>区域设置的重要性这里的参数,在将字符串转换为日期的答案中经常被忽略)

(please note the importance of the optional Locale argument here, this is often overlooked in answers about converting strings to dates)

下一步是计算这两个日期之间的差异。当您受限于标准Java SE API时,这是一项糟糕的工作。最好的办法是 java.util.Calendar

Your next step is calculating the difference between those 2 dates. This is a terrible job when you are restricted to the standard Java SE API. Best what you can get is the java.util.Calendar.

请注意当然可以减去毫秒并使用通常的算术运算符计算差值。

long differenceInMillis = date2.getTime() - date1.getTime();
// ...

但这种天真的做法不会飞跃多年考虑,更不用说夏令时和日期时间的本地特定更改

至于 java.util.Calendar 方法,基本上需要在计数器循环中使用 Calendar#add()获取年,月和日的经过值。这需要适当考虑闰年,夏令时和当地特定的干扰。

As to the java.util.Calendar approach, you basically need to use Calendar#add() in a counter loop to get the elapsed value for years, months and days. This takes leap years, daylight saving time and local-specific disturbances in time properly into account.

首先创建这个辅助方法以消除一些样板代码:

First create this helper method to eliminate some boilerplate code:

public static int elapsed(Calendar before, Calendar after, int field) {
    Calendar clone = (Calendar) before.clone(); // Otherwise changes are been reflected.
    int elapsed = -1;
    while (!clone.after(after)) {
        clone.add(field, 1);
        elapsed++;
    }
    return elapsed;
}

现在您可以按如下方式计算已用时间:

Now you can calculate the elapsed time as follows:

Calendar start = Calendar.getInstance();
start.setTime(date1);
Calendar end = Calendar.getInstance();
end.setTime(date2);

Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone(); // Otherwise changes are been reflected.
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;

System.out.format("%d years, %d months, %d days, %d hours, %d minutes, %d seconds", elapsed);

非常难看,是的。

如果你经常在Java中使用日期和时间,然后你可以找到 Joda time the walhalla 。这是一个具体的启动示例,说明如何使用纯Joda时间完成所有操作:

If you going to work with date and time in Java pretty often, then you may find Joda time the walhalla. Here's a concrete kickoff example of how you could do it all with pure Joda Time:

String string1 = "Oct 15, 2012 1:07:13 PM";
String string2 = "Oct 23, 2012 03:43:34 PM";

DateTimeFormatter dtf = DateTimeFormat.forPattern("MMM d, yyyy h:mm:ss a").withLocale(Locale.ENGLISH);

DateTime dateTime1 = dtf.parseDateTime(string1);
DateTime dateTime2 = dtf.parseDateTime(string2);
Period period = new Period(dateTime1, dateTime2);

PeriodFormatter formatter = new PeriodFormatterBuilder()
    .appendYears().appendSuffix(" years ")
    .appendMonths().appendSuffix(" months ")
    .appendWeeks().appendSuffix(" weeks ")
    .appendDays().appendSuffix(" days ")
    .appendHours().appendSuffix(" hours ")
    .appendMinutes().appendSuffix(" minutes ")
    .appendSeconds().appendSuffix(" seconds ")
    .printZeroNever()
    .toFormatter();

String elapsed = formatter.print(period);
System.out.println(elapsed);

好多了,对吧?复数s虽然需要一些工作,但这是不可能的。

Much better, right? The plural "s" needs some work though, but that's beyond the question.

这篇关于Java以这种格式减去两个日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆