Search code examples
freemarker

Transform a string into ISO datetime format | Freemarker


So I get the date and time which is, for example, 17.11.2021 and 12:44. Now I want to convert this date and time into the formate which Freemarker is using (yyyy-MM-dd hh:dd:mm:ss). However the problem here is that I can't convert it properly. I tried like:

${myDateTime?datetime.iso?string("yyyy-MM-dd HH:mm:ss")}

But this wont work. I always get an error message. Can anyone explain or show me the correct formation in this case ?


Solution

  • Assuming myDateTime is a String (and not already a Date object), and it looks like 17.11.2021 12:44, you can convert it to ISO format like this:

    ${myDateTime?datetime("dd.MM.yyyy HH:mm")?string.iso}
    

    Above myDateTime?datetime("dd.MM.yyyy HH:mm") converts the string to a Date (which is a format-independent representation), and then ?string.iso formats the Date with ISO format.

    Note that it would be much cleaner if myDateTime was a Date, not a String. Then you just do this: ${myDateTime?string.iso}