1

I have found some similar Que's on SO but had not find the solution.

I have today's Date as following: (Let's say this as Date1 and it's value as 2012-06-22)

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd");
    Date start = cal.getTime();
    String currentDate=dateformatter.format(start);

I'm retrieving 4 values from the user:

  • Particular Date (Assume 5)
  • Particular Month (Assume 1)
  • Particular Year (Assume 2012)
  • No. of days (Assume 7)

So this date, say Date2 becomes 2012-01-05 (yyyy-MM-dd) along with No. of days set to 7.


I want to compare Date 1 and Date 2-No. of days.

I know that by using following snippet, particular no. of days can be subtracted from a calender instance.

Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, -7);

But since I'm having Date2 in form of String, I'm not able to follow this approach.

Any help appreciated.

Edit:

From your suggestions, I'll be able to convert String to Date by using parse method of SimpleDateFormat.

Now I've 2 Date Objects.

  • How do I find Difference between them in terms of days, months, and years?
  • How to Subtract particular no. of days, say 7, from a particular date, say 2012-01-05?
4

4 回答 4

2

据我了解,您现在有两个日期,并且您想从日期中减去特定的天数。

首先,您可以使用SimpleDateFormat将日期转换为字符串和字符串转换为日期

现在减去天说7。你可以得到日期的时间并从中减去7 * 24 * 60 * 60 * 1000

     long daybeforeLong = 7 * 24 * 60 * 60 * 1000;
try {

Date todayDate = new Date();

long nowLong = todayDate.getTime();

Date beforeDate = new Date((nowLong - daybeforeLong));

    } 

catch (ParseException e) {
// TODO Auto-generated catch block
                                                e.printStackTrace();
}
于 2012-06-22T13:08:54.377 回答
2

用于SimpleDateFormatString(表示日期)转换为Date

例如 :

Date parsedDate  = new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-05");
于 2012-06-22T08:42:16.957 回答
2

如果您可以使用Joda Time代替Date/ Calendar,请这样做。它会让你的生活更轻松。

如果不是,听起来您不想格式化当前日期 - 相反,您想从用户那里解析 Date2

Date date2 = dateFormatter.parse(text);

然后您可以创建一个日历并减去特定的天数,或者(如果您正在谈论经过的时间 - 您需要考虑您在此处围绕 DST 转换和时区的行为)您可以只减去 7 * 24 * 60 * 60 * 1000 毫秒,从date2.getTime().

从根本上说,您应该尽可能早地转换字符串格式,并且仅在您真正需要时转换为字符串格式 - 当然不是为了比较。此数据的自然表示是DateCalendar(假设您坚持使用 JDK),因此请努力将您的数据转换为该表示。

不过,您有几个真正的“业务”问题需要考虑:

  • 您想将当前日期与用户给出的日期进行比较,还是将当前日期和时间与用户给出的日期进行比较?
  • 您想为用户输入使用哪个时区?
  • 您是在考虑经过的天数还是“逻辑”天数?因为由于 DST 转换,早于 1.30am 的 7 * 24 小时可能是 2.30am 或反之亦然

在尝试实现代码之前,您应该回答所有这些问题,因为它会影响您使用的表示。此外,在开始实施之前,为您能想到的所有内容编写单元测试。

于 2012-06-22T08:43:51.597 回答
1

我认为您可以使用 java 提供的 Comparator 来比较和排序日期。这是链接

希望你得到你想要的东西..

于 2012-06-22T08:44:07.460 回答