How to convert date in specific format in Freemarker template or javascript

耗尽温柔 提交于 2019-12-01 19:02:31

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}

Have you tried this?

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

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

Kristian Ivanov
function convertDate( 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

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>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
    var d = new Date("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>

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

@Component
public class OrderPresenter {

    private static final String FORMATTER_PARAM = "formatter";
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    private static final DateTimeFormatter FORMATTER =
            DateTimeFormatter.ofPattern(DATE_TIME_FORMAT).withZone(ZoneId.systemDefault());

    private Configuration configuration = prepareConfiguration();

    public String toHtmlPresentation(ClientDetails clientDetails) {
        try {
            Template template = configuration.getTemplate(CLIENT_DATA_TEMPLATE);
            Writer out = new StringWriter();
            template.process(toMap(clientDetails), out);
            return out.toString();
        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }

    private Configuration prepareConfiguration() {
        Configuration configuration = new Configuration(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;
    }

    private Map<String, Object> toMap(ClientDetails clientDetails) {
        Map<String, Object> res = new HashMap<>();
        res.put(CLIENT_DETAILS_PARAM, clientDetails);
        res.put(FORMATTER_PARAM, FORMATTER);
        return res;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!