How to return specific date format as JSON in Grails?

后端 未结 2 650
闹比i
闹比i 2021-01-30 23:32

In Grails, you can use the JSON converters to do this in the controller:

render Book.list() as JSON

The render result is

[
{\"i         


        
2条回答
  •  既然无缘
    2021-01-31 00:14

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

提交回复
热议问题