View Javadoc
1   package org.argeo.connect.util;
2   
3   import java.util.Calendar;
4   import java.util.GregorianCalendar;
5   
6   /** Utilities around date and time management. */
7   public class DateTimeUtils {
8   	public static Integer computeAge(Calendar dateOfBirth) {
9   		Calendar now = new GregorianCalendar();
10  		int factor = 0;
11  		if (now.get(Calendar.DAY_OF_YEAR) < dateOfBirth
12  				.get(Calendar.DAY_OF_YEAR))
13  			factor = -1;
14  		Integer age = now.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR)
15  				+ factor;
16  		return age;
17  	}
18  
19  	/* LENGTH AND DURATION MANAGEMENT */
20  	/** returns corresponding hours for a HH:MM:SS representation */
21  	public static long getHoursFromLength(long lengthInSeconds) {
22  		return (lengthInSeconds / (60 * 60)) % 60;
23  	}
24  
25  	/** returns corresponding minutes for a HH:MM:SS representation */
26  	public static long getMinutesFromLength(long lengthInSeconds) {
27  		return (lengthInSeconds / 60) % 60;
28  	}
29  
30  	/** returns corresponding seconds for a HH:MM:SS representation */
31  	public static long getSecondsFromLength(long lengthInSeconds) {
32  		return lengthInSeconds % 60;
33  	}
34  
35  	/** returns the length in second of a HH:MM:SS representation */
36  	public static long getLengthFromHMS(int hours, int min, int secs) {
37  		return 60 * 60 * hours + 60 * min + secs;
38  	}
39  
40  	/** Approximate the length in seconds in minute, round to the closest minute */
41  	public static long roundSecondsToMinutes(long lengthInSeconds) {
42  		long grounded = (lengthInSeconds / 60);
43  		if (getSecondsFromLength(lengthInSeconds) > 30)
44  			grounded++;
45  		return grounded;
46  	}
47  
48  	/** format a duration in second using a hh:mm:ss pattern */
49  	public static String getLengthFormattedAsString(long lengthInSeconds) {
50  		return String.format("%02d:%02d:%02d",
51  				getHoursFromLength(lengthInSeconds),
52  				getMinutesFromLength(lengthInSeconds),
53  				getSecondsFromLength(lengthInSeconds));
54  	}
55  
56  	private DateTimeUtils() {
57  	}
58  }