class DateFormatter implements TemplateMethodModelEx {

    @Override
    public Object exec(List args) throws TemplateModelException {
        if (args.size() != 3) {
            throw new IllegalArgumentException("Wrong arguments");
        }
        Object date = DeepUnwrap.unwrap((TemplateModel) args.get(0));
        String pattern = (String) DeepUnwrap.unwrap((TemplateModel) args.get(1));
        Locale locale = (Locale) DeepUnwrap.unwrap((TemplateModel) args.get(2));

        if (date instanceof LocalDate) {
            date = ((LocalDate)date).toDateTimeAtStartOfDay();
        }
        
        String formatted = "";
        if (date instanceof DateTime) {
            formatted = DateTimeFormat.forPattern(pattern).withLocale(locale).print((DateTime) date);
        } else if (date instanceof Date) {
            formatted = new SimpleDateFormat(pattern, locale).format((Date) date);
        } else if (date != null) {
            throw new IllegalArgumentException("Unsupported date type: " + date.getClass());
        }
        return formatted;
    }

}