rakesh
rakesh

Reputation: 165

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>
  <div class="reply">
   ${variable.createdOn}
  </div>
</#list>

The result i am getting is

Jan 09 2015 12:36:18 GMT+0530 (IST)

My preferable format is 09-01-2015

I need to remove rest of the time GMT, IST and so on.

How to convert this in Freemarker template or javascript.

Update

I tried to pass below like this

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

but it is giving error as

Exception: java.text.ParseException - Unparseable date: "Jan 09 2015 12:36:18 GMT+0530 (IST)"

Any help is Appreciated.

Thanks

Upvotes: 14

Views: 61108

Answers (6)

Beri
Beri

Reputation: 11620

This will format Your date:

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

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

Upvotes: 15

template.ftl

<#list listaCategoria as c>
   <tr>
      <td> ${c.dataCadastro?datetime("yyyy-MM-dd")?string("dd/MM/yyyy")}</td>
   </tr>
</#list>

RelatorioService.java

LocalDate dataCadastro = LocalDate.of(1995, 12, 7);

Result:

07/12/1995

Upvotes: 0

Yan Khonski
Yan Khonski

Reputation: 13083

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;
    }
}

Upvotes: 1

ddekany
ddekany

Reputation: 31152

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}

Upvotes: 22

Kristian Ivanov
Kristian Ivanov

Reputation: 111

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

Upvotes: 2

arman1991
arman1991

Reputation: 1166

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>

Upvotes: 1

Related Questions