Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.takecargo.utils;
- import java.util.Calendar;
- import java.util.Date;
- import java.util.concurrent.TimeUnit;
- public class TCDateUtils {
- // a general method, independent of unit of time--it's specified as a parameter. see here for possible values: http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/TimeUnit.html
- // e.g.: TimeUnit.DAYS, TimeUnit.HOURS
- public static long getDateDiff(Date date1, Date date2, TimeUnit timeUnit) {
- long diffInMillies = date2.getTime() - date1.getTime();
- return timeUnit.convert(diffInMillies,TimeUnit.MILLISECONDS);
- }
- // http://stackoverflow.com/a/10650881/557194
- public static long getDateDiffInDays(Date date1, Date date2) {
- long diffInMillis = date2.getTime() - date1.getTime();
- return TimeUnit.MILLISECONDS.toDays(diffInMillis); // http://stackoverflow.com/a/7829642/557194
- }
- // find out the number of hours (remainder) after the diffInDays value between date1 and date2
- public static int getHoursRemainderFromDateDiffInDays(Date date1, Date date2) {
- Calendar c1 = Calendar.getInstance();
- c1.setTime(date1);
- int hr1 = c1.get(Calendar.HOUR_OF_DAY);
- Calendar c2 = Calendar.getInstance();
- c2.setTime(date2);
- int hr2 = c2.get(Calendar.HOUR_OF_DAY);
- return Math.abs(hr2-hr1);
- }
- // find the "to date" calculated from today's date; return value should be equal to date2, above
- // @param days: will come from getDateDiffInDays()
- // @param hours: will come from getHoursRemainderFromDateDiffInDays()
- public static Date getToDateInXDaysAndXHours(long days, int hours) {
- Calendar toDate = Calendar.getInstance();
- toDate.add(Calendar.DAY_OF_YEAR, (int) days);
- toDate.add(Calendar.HOUR_OF_DAY, (int) ++hours); // ++hours because HOUR_OF_DAY is zero-based
- return toDate.getTime();
- }
- // ########### TEST CODE ###############
- public static void main(String[] args) {
- Calendar today = Calendar.getInstance();
- Calendar tomorrow = Calendar.getInstance();
- tomorrow.add(Calendar.DAY_OF_YEAR, 1);
- System.out.println(getDateDiffInDays(today.getTime(), tomorrow.getTime())); // OUTPUT: 1
- System.out.println(getDateDiff(today.getTime(), tomorrow.getTime(), TimeUnit.DAYS)); // OUTPUT: 1
- System.out.println(getDateDiff(today.getTime(), tomorrow.getTime(), TimeUnit.HOURS)); // OUTPUT: 24
- // add 6 hours to "tomorrow"'s point in time
- tomorrow.add(Calendar.HOUR_OF_DAY, 6);
- System.out.println(getDateDiff(today.getTime(), tomorrow.getTime(), TimeUnit.HOURS)); // OUTPUT: 30
- Date toDate = getToDateInXDaysAndXHours(
- getDateDiffInDays( // value: 1
- today.getTime(),
- tomorrow.getTime()
- ),
- getHoursRemainderFromDateDiffInDays( // value: 6
- today.getTime(),
- tomorrow.getTime()
- )
- );
- System.out.println(toDate); // OUTPUT (e.g. today == "Tue Jun 10 11:41:13 CEST 2013"): Tue Jun 11 17:41:13 CEST 2013
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment