Safely compares two calendars for equality in terms of date, time and timezone compatibility. - Java java.util

Java examples for java.util:Date Compare

Description

Safely compares two calendars for equality in terms of date, time and timezone compatibility.

Demo Code


//package com.java2s;
import java.util.Calendar;

public class Main {
    public static void main(String[] argv) throws Exception {
        Calendar o1 = Calendar.getInstance();
        Calendar o2 = Calendar.getInstance();
        System.out.println(safeDateTimeEquals(o1, o2));
    }//from w  w  w  . j a v  a2s .  c  o  m

    /**
     * Safely compares two calendars for equality in terms of date, time and timezone
     * compatibility.
     *
     * @param o1
     *            the first calendar to check
     * @param o2
     *            the second calendar to check
     * @return true if the calendars specify the same timestamp, false otherwise
     */
    public static boolean safeDateTimeEquals(Calendar o1, Calendar o2) {
        boolean result;

        if (o1 == null || o2 == null) {
            result = o1 == o2;
        } else {
            int off1 = o1.getTimeZone().getOffset(o1.getTimeInMillis());
            int off2 = o2.getTimeZone().getOffset(o2.getTimeInMillis());
            result = (o1.getTimeInMillis() == o2.getTimeInMillis());
            result = result && (off1 == off2);
        }

        return result;
    }
}

Related Tutorials