简体   繁体   中英

Comparing dates manually Java

I would like to compare two dates from either a string or parameter, parameter and parameter, or string and string in a class without using SimpleDateFormat or Date libraries, as well as testing. I have my constructors and getters all set and tested.

This is what I have for pseudo code.

public static void compare(int d, int m, int y)

If year in c1 is greater than c2, print c2 is earlier than c1
Else if month in c1 is greater than c2, print c2 is earlier than c1
Else if day in c1 is greater than c2, print c2 is earlier than c1

I'm not sure as to how I would compare two examples when each part of the date is already split up. I have a string method which takes the input as a string and parses that. Also the method should be called in another program, how would I call it in this instance where there are two variables being used?

You can try to convert the date into "days since 01-01-0000" (or into a unix timestamp ). The first one will work for all dates, the second one only from 1st January 1970 to 19th January 2038 (on 32 bit systems).

As these values are comparable numbers, simply use an if block and compare those.

Here's an example:

public int dateCompare(Date date1, Date date2) {

    if (date1.getYear() != date2.getYear())
        return (date1.getYear() - date2.getYear());
    if (date1.getMonth() != date2.getMonth())
        return (date1.getMonth() - date2.getMonth());
    return (date1.getDay() - date2.getDay());

}

Outputs:

  • <0 if date1 < date2
  • =0 if date1 = date2
  • >0 if date1 > date2

If you have already split your dates into day month year

expanding your method , this is just an example of manually and labor intensive checking

public static void compare(int firstDateDay, int firstDateMonth, int firstDateYear, int secondDateDay, int secondDateMonth, int secondDateYear)
{
   if (firstDateYear > secondDateYear)
   {
    // print secondDate is before first date 
   }
   else if (firstDateYear < secondDateYear )
   {
     // print secondDate is after first date 
   }
   else
  {
    // now check months 
  } 
 }

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