0

i have in my DB a date in this format 2016-03-11 09:20:22 how i can do if i want to compare with today date? I try to make this but i think that is not efficient:

private int getDayOfYear(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateString);
        GregorianCalendar greg = new GregorianCalendar();
        greg.setTime(date);
        return greg.get(greg.DAY_OF_MONTH);
    }
    private int getMonth(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateString);
        GregorianCalendar greg = new GregorianCalendar();
        greg.setTime(date);
        return greg.get(greg.MONTH);
    }
    private int getYear(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateString);
        GregorianCalendar greg = new GregorianCalendar();
        greg.setTime(date);
        return greg.get(greg.YEAR);
    }

Now i apply on today date and on db date this method, there is another way to compare two date?

  • Also a duplicate of [this](http://stackoverflow.com/q/19109960/642706) and [this](http://stackoverflow.com/q/15925509/642706) and others. Please search Stack Overflow thoroughly before posting. – Basil Bourque Apr 15 '16 at 07:54

1 Answers1

2

You can simply use the compareTo method:

date1.compareTo(date2);

There are other methods as well like before or after which you can use for Dates.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331