简体   繁体   中英

Subtracting and comparing Dates

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 ?

use SimpleDateFormat to convert String (representing date) to Date

For example :

Date parsedDate  = new SimpleDateFormat("yyyy-MM-dd").parse("2012-01-05");

If you can possibly use Joda Time instead of Date / Calendar , do so. It'll make your life easier.

If not, it sounds like you don't want to format the current date - instead, you want to parse Date2 from the user:

Date date2 = dateFormatter.parse(text);

Then you can either create a calendar and subtract a particular number of days, or (if you're talking about elapsed time - you need to think about your behaviour around DST transitions and time zones here) you could just subtract 7 * 24 * 60 * 60 * 1000 milliseconds from date2.getTime() .

Fundamentally, you should convert out of a string format as earlier as possible, and only convert to a string format when you really need to - certainly not for comparisons. The natural representation of this data is as a Date or Calendar (assuming you're sticking with the JDK), so work towards getting your data into that representation.

You have several genuine "business" questions to think about though:

  • Do you want to compare the current date with the date the user's given, or the current date and time with the date the user's given?
  • What time zone do you want to use for the user's input?
  • Are you thinking about elapsed days or "logical" days? Because 7 * 24 hours earlier than 1.30am may be 2.30am or vice versa, due to DST transitions

You should answer all those questions before you try to implement your code, as it will affect the representation you use. Also, write unit tests for everything you can think of before you start the implementation.

From my understanding you have two dates now and you want to subtract a particular number of days from date.

First you can use SimpleDateFormat to convert a date to string and string to date

Now to subtract days say 7. you can get time of the date and subtract 7*24*60*60*1000 from it

     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();
}

I think you can make use of Comparator provided by java will do work of comparing and sorting the dates too. here is the link

hope you get what you was looking for..

java.time

The question and the accepted answer have used the java.util Date-Time API and their parsing/formatting API, SimpleDateFormat which was appropriate thing to do using the standard library in 2012. In March 2014, Java 8 introduced the modern Date-Time API which supplanted the legacy API and since then it is highly recommended to use the modern Date-Time API.

Also, quoted below is a notice from the home page of Joda-Time :

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Requirements copied from your question:

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 ?

Solution using java.time , the modern Date-Time API:

With java.time , you can parse your date string into a LocalDate and then find the Period between this date and the current date (which you obtain with LocalDate.now() ). You can also subtract days, months, and years using methods like minusXxx / minus . You have similar methods ( plusXxx / plus ) for adding these units. Check the documentation of LocalDate to learn more about it.

Note : java.time API is based on ISO 8601 and therefore you do not need a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format (eg your date-time string, 2012-06-22 ).

Demo :

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;

class Main {
    public static void main(String[] args) {
        LocalDate then = LocalDate.parse("2012-06-22");
        LocalDate now = LocalDate.now();

        Period period = Period.between(then, now);
        System.out.println(period);
        System.out.printf("%d years %d months %d days%n", period.getYears(), period.getMonths(), period.getDays());

        // Examples of subtracting date units
        LocalDate sevenDaysAgo = now.minusDays(7);
        System.out.println(sevenDaysAgo);
        // Alternatively
        sevenDaysAgo = now.minus(7, ChronoUnit.DAYS);
        System.out.println(sevenDaysAgo);
    }
}

Output from a sample run:

P10Y6M27D
10 years 6 months 27 days
2023-01-11
2023-01-11

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM