3

My requirement is to compare a given date in a particular format in a given timezone to the current date in the same time zone. Also while comparing I have to ignore the timezone. And the comparison result should be: 0 or 1 or -1

One way I have tried is

  1. Set the required timezone
  2. Get the current date using "new Date()" format it using "yyyy-MM-dd" and then parse it again to get the date object
  3. Use the same formatter for supplied date string to be compared
  4. Then compare both dates using compareTo which gives the desired result
public void compareDate(){

    TimeZone.setDefault(TimeZone.getTimeZone("America/New_York"));
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    Date todayDate = dateFormatter.parse(dateFormatter.format(new Date()));
    Date date = dateFormatter.parse("2021-02-28");
    System.out.println(todayDate.compareTo(date));

}

But the above looks inefficient to me.

Other way could be to get both the dates like below and then compare?

public static Date getDateWithoutTimeUsingCalendar() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    return calendar.getTime();
}

Can someone please suggest a better alternative?

Just one thing, timezone and comparing without time has to be there.

Gautham M
  • 4,816
  • 3
  • 15
  • 37
Deepak Kumar
  • 843
  • 1
  • 7
  • 19
  • What about converting the times to their Long base values and use Long.Compare(long, long)? Would need a code example so we know what you're working with. –  Mar 01 '21 at 20:06
  • 1
    confused: date without time in timezone?? maybe some examples would help understanding. Anyway, I would try with `LocalDate` (date without time (and without timezone)) –  Mar 01 '21 at 20:10
  • @user15244370 added code – Deepak Kumar Mar 01 '21 at 20:16
  • @RandomCoder_01 added code – Deepak Kumar Mar 01 '21 at 20:22

1 Answers1

5

The java.util date-time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.*

Demo using java.time API (modern date-time API):

import java.time.DateTimeException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Tests
        try {
            System.out.println(compareWith("2021-02-28", "yyyy-MM-dd", "Asia/Calcutta"));
            System.out.println(compareWith("2021/03/03", "yyyy/MM/dd", "Asia/Calcutta"));
        } catch (DateTimeException e) {
            System.out.println("Date string parsing error occured.");
        }
    }

    static int compareWith(String strDate, String format, String timezone) throws DateTimeException {
        ZoneId zoneId = ZoneId.of(timezone);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format, Locale.ENGLISH);

        ZonedDateTime today = ZonedDateTime.now(zoneId).with(LocalTime.MIDNIGHT);
        ZonedDateTime date = LocalDate.parse(strDate, dtf).atStartOfDay(zoneId);

        return today.compareTo(date);
    }
}

Output:

1
-1

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


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110