Sightly Date Formatting With Javascript Use API
Sep 6, 2015 · 2 minute read · CommentsAEMSightlyJavascript
In Sightly we don’t have a built-in date format utility. In this post we will show a way we can format dates using the Javascript Use-API.
An example on how to achieve the same using the Java Use-API can be found in this post.
Let’s take a look at the code. It is a very simple example and can be seen below:
#dateformat.html
<h1 data-sly-use.formatter="${'dateformat.js' @ date=currentPage.lastModified.time, mask='MM/dd/yyyy'}">
Last modified date formatted: ${formatter.formattedDate}
</h1>
That’s the script that will display the HTML for the component, as we can see it is very simple.
With the data-sly-use we define the script that we will use, in this case dateformat.js, and we pass two parameters to the script:
- date - the date that is going to be formatted taken from the currentPage;
- mask - that is the pattern that we will use to format the date;
Then we print the formatted date using the object defined in data-sly-use directive:
${formatter.formattedDate}
Now let’s take a look at the dateformat.js script:
//dateformat.js
use(function () {
var formattedDate = new java.text.SimpleDateFormat(this.mask).format(this.date);
return {
formattedDate: formattedDate
};
});
As we can see it is a very simple javascript code. For date formatting, we use the SimpleDateFormat class. The parameters passed are retrieved using this.date and this.mask.mask In the end we return a object with a property containing the formatted date.
I hope you enjoyed this post.
Thanks, See you in the next post.