package org.openslx.dozmod.gui.helper; import java.util.Calendar; import java.util.Date; import javax.swing.JSpinner; import org.apache.log4j.Logger; import org.jdatepicker.JDatePicker; public class DateTimeHelper { private final static Logger LOGGER = Logger.getLogger(DateTimeHelper.class); /** * Returns the Date composed of the given datePicker's date and the given * timeSpinner's time. Returns null if the model of either one doesn't * return a Date instance. * * @param datePicker to extract the date from * @param timeSpinner to extract the time from * @return Date represented by datePicker's day and timeSpinner's time, * {@code null} on error */ public static Date getDateFrom(JDatePicker datePicker, JSpinner timeSpinner) { // start date from the DatePicker int years = datePicker.getModel().getYear(); int months = datePicker.getModel().getMonth(); int days = datePicker.getModel().getDay(); Object oTime = timeSpinner.getValue(); if (!(oTime instanceof Date) || years < 1000) return null; // start time from the Spinner Date time = (Date)oTime; Calendar calendar = Calendar.getInstance(); calendar.setTime(time); int hours = calendar.get(Calendar.HOUR_OF_DAY); int minutes = calendar.get(Calendar.MINUTE); // build the time from the single values calendar.set(years, months, days, hours, minutes); Date date = calendar.getTime(); return date; } public static Date addDaysTo(Date start, int days) { Calendar calendar = Calendar.getInstance(); calendar.setTime(start); calendar.add(Calendar.DAY_OF_MONTH, days); return calendar.getTime(); } /** * Calculate the number of days between dates * * @param start start date to use * @param end end date * @return Rounded number of days */ public static int calculatePeriodInDays(Date start, Date end) { if (end.before(start)) return 0; return Math.round((end.getTime() - start.getTime()) / 86400000f); } /** * Helper to set the given date's time to midnight. * * @param date * @return date with hour, minute and seconds set to 23:59:59 */ public static Date endOfDay(final Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); return cal.getTime(); } }