Search code examples
javascriptdatefreemarker

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


Solution

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