How to return specific date format as JSON in Grails?

陌路散爱 提交于 2019-12-02 16:21:40

There is a simple solution: Since Grails 1.1 the Converters have been rewritten to be more modular. Unfortunately I didn't finish the documentation for that. It allows now to register so called ObjectMarshallers (simple Pogo/Pojo's that implement the org.codehaus.groovy.grails.web.converters.marshaller.ObjectMarshaller interface).

To achieve your desired output, you could register such an ObjectMarshaller in BootStrap.groovy that way:

import grails.converters.JSON;

class BootStrap {

     def init = { servletContext ->
         JSON.registerObjectMarshaller(Date) {
            return it?.format("dd-MM-yyyy")
         }
     }
     def destroy = {
     }
}

There are several other ways to customize the output of the Converters and I'll do my best do catch up with the documentation asap.

Or you could work at the Date level itself. This might not be exactly what you want but it could spark an idea for a solution that would work consistently across your whole app.

def doWithDynamicMethods = {ctx ->

  def customDateToString = {->
        def dateFormat = "dd MMM yyyy"
        def timeFormat = "hh:mm:ss a"

        def timeCheck = new java.text.SimpleDateFormat("hh:mm:ss SSS a")
        def formattedTime = timeCheck.format(delegate)
        def formatString = dateFormat
        if (formattedTime != "12:00:00 000 AM") 
                              formatString = "$formatString $timeFormat"
        def formatter = new java.text.SimpleDateFormat("$formatString")
        formatter.format(delegate)
    }

    Date.metaClass.toString = customDateToString;
    java.sql.Timestamp.metaClass.toString = customDateToString;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!