Java Timestamp Compare dateDifference(Timestamp one, Timestamp two)

Here you can find the source of dateDifference(Timestamp one, Timestamp two)

Description

Returns the number of days between the beginning of two days.

License

Open Source License

Parameter

Parameter Description
one first <code>Timestamp</code> value
two second <code>Timestamp</code> value

Return

the absolute value of the number of days between the two given Timestamp

Declaration

public static Integer dateDifference(Timestamp one, Timestamp two) 

Method Source Code

//package com.java2s;
/*/*from   w  ww . j a v a 2  s  .  co m*/
 * Copyright (c) Open Source Strategies, Inc.
 *
 * Opentaps is free software: you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Opentaps is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Opentaps.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.sql.Timestamp;

import java.util.Calendar;

public class Main {
    /** Number of milliseconds in a day. */
    public static final long MS_IN_A_DAY = 24 * 60 * 60 * 1000;

    /**
     * Returns the number of days between the beginning of two days.
     * This value is always positive.
     * @param one first <code>Timestamp</code> value
     * @param two second <code>Timestamp</code> value
     * @return the absolute value of the number of days between the two given <code>Timestamp</code>
     */
    public static Integer dateDifference(Timestamp one, Timestamp two) {
        Calendar first = Calendar.getInstance();
        Calendar second = Calendar.getInstance();
        first.setTime(one);
        second.setTime(two);

        // set to the beginning of the day
        first.set(Calendar.HOUR_OF_DAY, 0);
        first.set(Calendar.MINUTE, 0);
        first.set(Calendar.SECOND, 0);
        second.set(Calendar.HOUR_OF_DAY, 0);
        second.set(Calendar.MINUTE, 0);
        second.set(Calendar.SECOND, 0);

        double msdiff = first.getTimeInMillis() - second.getTimeInMillis();
        long days = Math.round(msdiff / MS_IN_A_DAY);
        return new Integer((int) Math.abs(days));
    }
}

Related

  1. compareTimestamp(final Timestamp d1, final Timestamp d2)
  2. compareTimestamps(Timestamp minTimestamp, Timestamp maxTimestamp)
  3. compareTimestamps(Timestamp timestamp1, Timestamp timestamp2)
  4. dateDiff(Timestamp t1, Timestamp t2, int type)