NowELFunction implements ELFunction { @Override public String evalute(String... args) { SimpleDateFormat dateFormat = null; if (args != null) { switch (args.length) { case 1: dateFormat = new SimpleDateFormat(args[0]); return dateFormat.format(Calendar.getInstance().getTime()); case 2: Calendar now = Calendar.getInstance(); String unit = args[1].substring(args[1].length() - 1); String amountStr = args[1].substring(0, args[1].length() - 1); if (isInteger(amountStr)) { int amount = Integer.parseInt(amountStr); switch (unit) { case "m": now.add(Calendar.MINUTE, amount); break; case "H": now.add(Calendar.HOUR, amount); break; case "d": now.add(Calendar.DATE, amount); break; case "M": now.add(Calendar.MONTH, amount); break; case "y": now.add(Calendar.YEAR, amount); break; default: break; } } dateFormat = new SimpleDateFormat(args[0]); return dateFormat.format(now.getTime()); default: return String.valueOf(System.currentTimeMillis()); } } return String.valueOf(System.currentTimeMillis()); }  @Override String evalute(String... args);  }
@Test public void testSimpleEvaluation() { long before = System.currentTimeMillis(); NowELFunction function = new NowELFunction(); String result = function.evalute(); long resultLong = Long.parseLong(result); long after = System.currentTimeMillis(); assertTrue(before <= resultLong); assertTrue(after >= resultLong); }
@Test public void testPatternEvaluation() { Calendar currentDate = Calendar.getInstance(); NowELFunction function = new NowELFunction(); String result = function.evalute("dd/MM/yyyy HH:mm:ss"); int day = currentDate.get(Calendar.DAY_OF_MONTH); int month = currentDate.get(Calendar.MONTH); int year = currentDate.get(Calendar.YEAR); String dateString = (day < 10 ? "0" + day : day) + "/" + (++month < 10 ? "0" + month : month) + "/" + year; assertTrue(result.startsWith(dateString)); }
@Test public void testPatternDeltaEvaluation() { Calendar currentDate = Calendar.getInstance(); NowELFunction function = new NowELFunction(); String result = function.evalute("dd/MM/yyyy HH:mm:ss", "1d"); currentDate.add(Calendar.DAY_OF_YEAR, 1); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss"); String dateString = dateFormat.format(currentDate.getTime()); assertTrue(result.startsWith(dateString)); result = function.evalute("dd/MM/yyyy HH:mm:ss", "1M"); currentDate.add(Calendar.DAY_OF_YEAR, -1); currentDate.add(Calendar.MONTH, 1); dateString = dateFormat.format(currentDate.getTime()); assertTrue(result.startsWith(dateString)); }