Skip to content Skip to sidebar Skip to footer

How To Convert Date In Specific Format In Freemarker Template Or Javascript

From json, i am getting the value as 'createdOn': 'Jan 08 2015 20:40:56 GMT+0530 (IST)', I am Accessing in FTL <#list variables as variable>
$

Solution 1:

First of all, what format is that at all? I mean, if you can influence someone to use a standard format instead (ISO, mostly) that will help everyone. Anyway, FreeMarker isn't a date parser library, but actually you can do something like this:

<#-- Settings you need -->
<#setting date_format="dd-MM-yyyy">
<#setting locale="en_US">

<#-- The string that comes from somewhere: -->
<#assign createdOn = 'Jan 08 2015 20:40:56 GMT+0530 (IST)'>

<#--1. Tell FreeMarker to convert string to real date-time value
  2. Convert date-time value to date-only value
  3. Let FreeMarker format it according the date_format setting
-->
${createdOn?datetime("MMM dd yyyy HH:mm:ss 'GMT'Z")?date}

Solution 2:

Have you tried this?

"${variable.createdOn?datetime?string('dd-MM-yyyy')}"

Here is link to documentation: http://freemarker.org/docs/ref_builtins_date.html

Solution 3:

functionconvertDate( date ){
    dateSplit = date.toString().split( ' ' );
    dateSplit[1] = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1).toString() : date.getMonth() + 1;
    return dateSplit[2] + '-' + dateSplit[1] +  '-' + dateSplit[3];
}

convertDate(new Date());

This should do the job. You can tweak it additionally

Solution 4:

You can create your own custom function and use getDate, getMonth and getFullYear methods to format your date.

Note that you must parse your string date format into Date object.

<!DOCTYPE html><html><body><p>Click the button to display todays day of the month in dd-MM-yyyy format.</p><buttononclick="myFunction()">Try it</button><pid="demo"></p><script>functionmyFunction() {
    var d = newDate("Jan 08 2015 20:40:56 GMT+0530 (IST)"); //parsing your string date format into Date object.var z = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear();
   
    document.getElementById("demo").innerHTML = z;
}
</script></body></html>

Solution 5:

I went this way. I created an object - formatter and pass it into template model. And I call formatter.format(date) in the template.

template.ftl

<div class="historyOrderItem">
    <div><div>Created <#if order.created??>${formatter.format(order.created)}</#if></div><div>Amount ${order.amount!}</div><div>Currency ${order.currency!}</div></div>

OrderPresenter.java

@ComponentpublicclassOrderPresenter {

    privatestatic final StringFORMATTER_PARAM = "formatter";
    privatestatic final StringDATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    privatestatic final DateTimeFormatterFORMATTER =
            DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).withZone(ZoneId.systemDefault());

    privateConfiguration configuration = prepareConfiguration();

    publicStringtoHtmlPresentation(ClientDetails clientDetails) {
        try {
            Template template = configuration.getTemplate(CLIENT_DATA_TEMPLATE);
            Writer out = newStringWriter();
            template.process(toMap(clientDetails), out);
            return out.toString();
        } catch (IOException | TemplateException e) {
            thrownewRuntimeException(e);
        }
    }

    privateConfigurationprepareConfiguration() {
        Configuration configuration = newConfiguration(Configuration.VERSION_2_3_23);
        configuration.setDefaultEncoding(ENCODING);
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setLogTemplateExceptions(NOT_TO_LOG_EXCEPTIONS);
        configuration.setClassForTemplateLoading(OrderPresenter.class, TEMPLATES_FOLDER);
        return configuration;
    }

    privateMap<String, Object> toMap(ClientDetails clientDetails) {
        Map<String, Object> res = newHashMap<>();
        res.put(CLIENT_DETAILS_PARAM, clientDetails);
        res.put(FORMATTER_PARAM, FORMATTER);
        return res;
    }
}

Post a Comment for "How To Convert Date In Specific Format In Freemarker Template Or Javascript"