2

I have date input as "20170101"(YYYYMMDD) , i just have to write freemarker template to convert or format the above date into "2017-01-01 00:00:00" (YYYY-MM-DD HH:MM:SS) as date-time above format.

I have tried like

<#assign createdOn = '20170101'> Dates="${createdOn?datetime("MMM dd yyyy HH:mm:ss")?date}

But it returns error as "The string doesn't match the expected date/time/date-time format. The string to parse was: "20170101". The expected format was: "MMM dd yyyy HH:mm:ss". The nested reason given follows: Unparseable date: "20170101"

Please tel me how to parse to my expected date time format from my given input?

Alfabravo
  • 7,493
  • 6
  • 46
  • 82
Naveen
  • 43
  • 2
  • 9

2 Answers2

2

If your input is "20170101", then expected format is "YYYYMMDD".

So replace "MMM dd yyyy HH:mm:ss" with "yyyyMMdd".

  • Hi eugenioflima,My expected format is not the input as you said,Input is YYYYMMDD,expected is "2017-01-01 00:00:00" (YYYY-MM-DD HH:MM:SS),Please suggest appropriate solution – Naveen Sep 13 '18 at 05:18
  • 1
    @eugenioflima The format is actually `yyyyMMdd` (as defined by Java `SimpleDateFormat`). – ddekany Sep 13 '18 at 09:58
  • 1
    You're right, @ddekany. I focused only on the mismatch between input value and the expected format. Your answer is perfect. – eugenioflima Sep 17 '18 at 12:04
1

If you have a string (not a java.util.Date), as in your example, then first it must be parsed to a Date via ?date/?datetime?time, where you provide the format of the string. (Consider, something like 20180102 can't be parsed unambiguously if the format is not provided.) At that point you can just print the value, and it will be formatted according the default datetime_format (or date_format, etc.) configured for FreeMarker. If that format it not good, then you can force another with ?string(theFormatYouWant). So, in your case:

<#assign createdOn = '20170101'>
Date="${createdOn?datetime("yyyyMMdd")?string("yyyy-MM-dd HH:mm:ss")}

But again, generally, you don't need the ?string(...), instead configure your preferred format globally.

ddekany
  • 29,656
  • 4
  • 57
  • 64
  • Hi ddekany,Above code does wonder,you are awesome,,,Thank you very much for your great help,I just want to learn more about String and date and Integration of java functions of Freemarker templates,do you have any blogs for reference,If so please share it...Thanks again.. – Naveen Sep 13 '18 at 18:43
  • @Naveen I think the best source is the official documentation... and searching on Stackoverflow. Also, you are supposed to accept the answer (click the check mark). – ddekany Sep 13 '18 at 20:33