1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
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();
}
}
|