public
Last active

Time Parser

  • Download Gist
gistfile1.java
Java
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 80
public class StandardParser implements TimeParser {
 
private Logger logger;
 
// units used in SimpleDateFormat
private String[] unitFormats = { "yyyy", "MM", "dd", "HH", "mm", "ss" };
 
private SimpleDateFormat formatter;
 
// this is a relative time, and cannot be directly compared to the current date. This is because
// the SimpleDateFormatter is not always given all units, and will then resort to defaults
private Date triggerDate;
 
private Date prevDate;
 
public StandardParser(Logger logger) {
this.logger = logger;
}
 
@Override
public void create(Element element) {
String rawDate = element.getText();
 
// get biggest defined unit by counting tacks (-)
String triggerStrings[] = rawDate.split("-");
 
// create simple format by adding from the units[] list
String pattern = "";
for (int i = triggerStrings.length; i > 0; i--) {
pattern += unitFormats[unitFormats.length - i] + "-";
}
 
// remove extra tack from end
pattern = pattern.substring(0, pattern.length() - 1);
 
formatter = new SimpleDateFormat(pattern);
triggerDate = parse(formatter, rawDate);
if (triggerDate == null)
return;
 
String prevDateString = formatter.format(new Date());
prevDate = parse(formatter, prevDateString);
}
 
@Override
public boolean isCurrent() {
 
String currentDateString = formatter.format(new Date());
Date currentDate = parse(formatter, currentDateString);
 
System.out.println("Trigger: " + triggerDate + "\nprevious: " + prevDate + "\ncurrent: " + currentDate);
 
if (triggerDate.after(prevDate) && triggerDate.before(currentDate)) {
String prevDateString = formatter.format(new Date());
prevDate = parse(formatter, prevDateString);
return true;
} else {
String prevDateString = formatter.format(new Date());
prevDate = parse(formatter, prevDateString);
return false;
}
}
 
@Override
public boolean canParse(String parseMode) {
return parseMode.equals("standard");
}
 
private Date parse(SimpleDateFormat formatter, String toParse) {
Date date = null;
try {
date = formatter.parse(toParse);
} catch (ParseException e) {
logger.log("Invalid Standard date formatting: " + toParse, LogSource.ERROR, LogSource.BEHAVIOUR, 1);
return null;
}
 
return date;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.