Article updated on April 26, 2017

NOTE: From AEM6.3 you have now native support for Date/Number formatting: See my blogpost here: http://blogs.adobe.com/experiencedelivers/uncategorized/new-htl-features-aem6-3/

Now that more and more people use the HTML Template Language (HTL), formerly known as Sightly, an often heard question is how to do date formatting in HTL. In this small blog post, I will show you a way to achieve that.

HTL template

In the example below, I will format the last-modified date of the page, displaying it in a “dd/MM/yyyy” format.

<sly data-sly-use.date="${'com.yourProject.DateFormatter' @ date=currentPage.lastModified,
     format='dd/MM/yyyy'}">${date.value}</sly>

Two parameters are sent from HTL to the Java class: “date” and “format”. In return, the Java class makes the “value” property available for the template to display the formatted date.

Sling Model logic

I use Sling Model for this, together with the SimpleDateFormat class:

package com.yourProject;

import java.text.SimpleDateFormat;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.models.annotations.Model;

@Model(adaptables=SlingHttpServletRequest.class)
public class DateFormatter {

    @Inject
    private Calendar date;

    @Inject
    private String format;

    public String value;

    @PostConstruct
    protected void init() {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        value = formatter.format(date.getTime());
    }
}

The code in the Java-class is quite simple because “date” and “format” get injected automatically by the Sling Model Java annotations. Therefore the only “real” code you need to write is to call the format() method.

Hopefully this gives you an idea how to achieve things like formatting with the HTML Template Language.

@heervisscher

Read-on

Other posts on the topic:

And here other resources to learn more about it: