Here you can find the source of getTimeDifference(String unit, Calendar start, Calendar end)
public static long getTimeDifference(String unit, Calendar start, Calendar end)
//package com.java2s; /*/* www . java2s. c o m*/ * Copyright (C) 2014 Dell, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.util.Calendar; import java.util.Hashtable; public class Main { final static long ONE_SECOND = 1000; final static long ONE_MINUTE = ONE_SECOND * 60; final static long ONE_HOUR = ONE_MINUTE * 60; final static long ONE_DAY = ONE_HOUR * 24; final static long ONE_WEEK = ONE_DAY * 7; static Hashtable<String, Integer> functions = new Hashtable<>(); public static long getTimeDifference(String unit, Calendar start, Calendar end) { long diff = end.getTimeInMillis() - start.getTimeInMillis(); switch (functions.get(unit)) { case 20: // minute diff = diff / ONE_MINUTE; break; case 21: //hour diff = diff / ONE_HOUR; break; case 22: //day diff = diff / ONE_DAY; break; case 23: //week diff = diff / ONE_WEEK; break; case 24: //month diff = end.get(Calendar.YEAR) - start.get(Calendar.YEAR); diff = diff * 12 + end.get(Calendar.MONTH) - start.get(Calendar.MONTH); break; case 25: //year diff = end.get(Calendar.YEAR) - start.get(Calendar.YEAR); break; case 26: //quarter diff = end.get(Calendar.YEAR) - start.get(Calendar.YEAR); diff = diff * 12 + end.get(Calendar.MONTH) - start.get(Calendar.MONTH); diff = diff / 3; break; case 27: //second diff = diff / ONE_SECOND; break; default: throw new IllegalArgumentException("Unsupported date time unit:" + unit); } return diff; } }