Skip to content

Instantly share code, notes, and snippets.

@marlonlom
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marlonlom/13dc900ffe7f5d2d6dd5 to your computer and use it in GitHub Desktop.
Save marlonlom/13dc900ffe7f5d2d6dd5 to your computer and use it in GitHub Desktop.
Custom utility for date difference functionality, using a date string against current date. this method must be used following the pattern "EEE, dd MMM yyyy HH:mm:ss Z". but you can change this setting pattern values on utility class. Provided utility and demo. This utility was made using joda-time-2.7.jar
package co.malm.demos.datediff;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import co.malm.demos.datediff.util.DateDiffUtil;
public class CustomDateDiffExample {
public static void main(String[] args) {
final Date current = new Date();
System.out.println("current=" + current.toString());
try {
for (String dateText : sampleDates) {
Date parsedDate = sdf.parse(dateText);
String processDiff = DateDiffUtil.getInstance().processDiff(dateText, current);
String format_msg = "datediff(%s)\t=\t[%s]";
System.out.println(String.format(format_msg, parsedDate.toString(), processDiff));
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static final String DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss Z";
private static final SimpleDateFormat sdf = new SimpleDateFormat(DATE_PATTERN,
Locale.ENGLISH);
final static ArrayList<String> sampleDates = new ArrayList<String>();
static {
sampleDates.add("Sun, 05 Apr 2015 03:09:10 +0000");
sampleDates.add("Thu, 02 Apr 2015 00:18:10 +0000");
sampleDates.add("Mon, 23 Mar 2015 04:17:20 +0000");
sampleDates.add("Sat, 21 Mar 2015 03:49:55 +0000");
sampleDates.add("Thu, 19 Mar 2015 16:18:06 +0000");
sampleDates.add("Thu, 19 Mar 2015 15:45:21 +0000");
sampleDates.add("Mon, 16 Mar 2015 02:44:12 +0000");
sampleDates.add("Wed, 11 Mar 2015 17:19:18 +0000");
sampleDates.add("Sun, 08 Mar 2015 15:15:51 +0000");
sampleDates.add("Sat, 07 Mar 2015 03:29:00 +0000");
sampleDates.add("Sun, 01 Mar 2015 06:40:00 +0000");
}
}
package co.malm.demos.datediff.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Hours;
import org.joda.time.Minutes;
import org.joda.time.Months;
import org.joda.time.Seconds;
import org.joda.time.Weeks;
import org.joda.time.Years;
/**
* Utility class for calculating the minor date difference using two dates: the
* input date, provided by user, and the current datetime. <br/>
* This class is a singleton, and its main method can be used for calculating
* datediff's from an list, and inside loop, it must be used like this:<br/>
*
* <pre>
* DateDiffUtil.getInstance().processDiff(dateText, now);
* </pre>
*
* @author marlonlom
*/
public class DateDiffUtil {
/**
* Returns singleton instance for {@linkplain DateDiffUtil}
*
* @return instance
*/
public static DateDiffUtil getInstance() {
return INSTANCE;
}
/**
* Simple class name ,for logging purposes only
*/
private static final String TAG = DateDiffUtil.class.getSimpleName();
/**
* Date pattern for parsing
*/
private static final String DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss Z";
/**
* Simple date format instance for converting date strings
*
* @see SimpleDateFormat
*/
private static final SimpleDateFormat SDF = new SimpleDateFormat(
DATE_PATTERN, Locale.ENGLISH);
/**
* Singleton instance for {@linkplain DateDiffUtil}
*/
private static final DateDiffUtil INSTANCE = new DateDiffUtil();
/**
* Logger utility for the class
*/
private static final Logger LOGGER = Logger.getLogger(TAG);
/**
* Private constructor
*/
private DateDiffUtil() {
super();
}
/**
* Calculates time differences using two dates, and stores it into a
* {@linkplain Map} object.
*
* @param map
* calculations data
* @param dt1
* first date for diff
* @param dt2
* second date for diff
* @see DateTime
* @see Years
* @see Months
* @see Weeks
* @see Days
* @see Hours
* @see Minutes
* @see Seconds
*/
private void calculate(HashMap<String, Integer> map,
DateTime dt1, DateTime dt2) {
final int SECONDS_IN_MINUTE = 60;
final int MINUTES_IN_HOUR = 60;
final int HOURS_IN_DAY = 24;
final int DAYS_IN_MONTH = 31;
final int MONTHS_IN_YEAR = 12;
final int WEEKS_IN_DAY = 7;
int diffYears = Years.yearsBetween(dt1, dt2).getYears();
if (diffYears > 0) {
map.put("years", diffYears);
}
int diffMonths = Months.monthsBetween(dt1, dt2).getMonths();
if (diffMonths >= 1 && diffMonths < MONTHS_IN_YEAR) {
map.put("months", diffMonths);
}
int diffWeeks = Weeks.weeksBetween(dt1, dt2).getWeeks();
if (diffWeeks >= 1 && diffWeeks < WEEKS_IN_DAY) {
map.put("weeks", diffWeeks);
}
int diffDays = Days.daysBetween(dt1, dt2).getDays();
if (diffDays >= 1 && diffDays < DAYS_IN_MONTH) {
map.put("days", diffDays);
}
int diffHours = Hours.hoursBetween(dt1, dt2).getHours();
if (diffHours >= 1 && diffHours < HOURS_IN_DAY) {
map.put("hours", diffHours);
}
int diffMinutes = Minutes.minutesBetween(dt1, dt2).getMinutes();
if (diffMinutes >= 1 && diffMinutes < MINUTES_IN_HOUR) {
map.put("minutes", diffMinutes);
}
int diffSeconds = Seconds.secondsBetween(dt1, dt2).getSeconds();
if (diffSeconds >= 1 && diffSeconds < SECONDS_IN_MINUTE) {
map.put("seconds", diffSeconds);
}
}
/**
* Returns minor value for calculated datetime differences
*
* @param map
* stored datetime difference calculations
* @return minor key=value for time calculation
*/
private String chooseMinorDiff(HashMap<String, Integer> map) {
Set<String> keySet = map.keySet();
String minorKey = "";
Integer minorValue = Integer.MAX_VALUE;
for (String diffKey : keySet) {
Integer diffValue = map.get(diffKey);
int comparison = Math.min(minorValue, diffValue);
if (comparison == diffValue) {
minorKey = diffKey;
minorValue = diffValue;
}
}
String minValueText = String.valueOf(minorValue.intValue());
return minorKey.concat("=").concat(minValueText);
}
/**
* Prepares date difference calculations, and returns the minor value
* calculated in time terms
*
* @param textdate
* text date for compare
* @return minor date difference calculated
*/
public String diff(String textdate) {
StringBuilder resultDiff = new StringBuilder();
try {
Date date0 = parseDate(textdate);
resultDiff.append(perform(date0, new Date()));
} catch (Exception e) {
LOGGER.severe(e.getMessage());
}
return resultDiff.toString();
}
/**
* Prepares date difference calculations, and returns the minor value
* calculated in time terms
*
* @param textdate
* text date for compare
* @param current
* current date
* @return minor date difference calculated
*/
public String diff(String textdate, Date current) {
StringBuilder resultDiff = new StringBuilder();
try {
Date date0 = parseDate(textdate);
resultDiff.append(perform(date0, current));
} catch (Exception e) {
LOGGER.severe(e.getMessage());
}
return resultDiff.toString();
}
/**
* Prepares date difference calculations, and returns the minor value
* calculated in time terms
*
* @param textdate0
* text date for compare
* @param textdate1
* text date for compare
* @return minor date difference calculated
*/
public String diff(String textdate0, String textdate1) {
StringBuilder resultDiff = new StringBuilder();
try {
Date date0 = parseDate(textdate0);
Date date1 = parseDate(textdate1);
resultDiff.append(perform(date0, date1));
} catch (Exception e) {
LOGGER.severe(e.getMessage());
}
return resultDiff.toString();
}
/**
* Parses date string using defined pattern
*
* @param textdate
* date string
* @return parsed {@linkplain Date} instance
* @throws Exception
*/
private Date parseDate(String textdate) throws Exception {
return SDF.parse(textdate);
}
/**
* Performs date difference using selected dates
*
* @param resultDiff text that stores result
* @param date0 input date for diff
* @param date1 input date for diff
*/
private String perform(Date date0, Date date1) {
StringBuilder resultDiff = new StringBuilder();
DateTime dt1 = new DateTime(date0);
DateTime dt2 = new DateTime(date1);
if (dt1.isBefore(dt2)) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
calculate(map, dt1, dt2);
resultDiff.append(chooseMinorDiff(map));
}
return resultDiff.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment