Overriding the Groovy method java.util.Date toString

I have a Grails application (version 2.5.0; Groovy version 2.4.3) in which I had the CustomPropertyEditorRegistry property to override date formats when using the fieldvalue value.

I installed the ElasticSerach Grails plugin version 0.0.4.4, after installation I noticed that the custom properties editor no longer works. In an attempt to temporarily fix the problem, I decided to simply override the java.util.Date toString () method using Groovy metaprogramming.

I added this to Bootstrap.groovy:

Date.metaClass.toString = {
   return delegate.format("MM/dd/yyyy HH:mm")
}

However, when I went to the Grails console (using the Grails Console plugin):

new Date("Fri Jun 12 12:36:02 EDT 2015") as String == "Fri Jun 12 12:36:02 EDT 2015"
new Date("Fri Jun 12 12:36:02 EDT 2015").toString() == "06/12/2015 12:36"

println(new Date("Fri Jun 12 12:36:02 EDT 2015")) // prints Fri Jun 12 12:36:02 EDT 2015
println(new Date("Fri Jun 12 12:36:02 EDT 2015").toString()) // prints 06/12/2015 12:36 

/ toString() . ElasticSearch Grails Plugin GitHub, № 115,

EDIT:

Grails Groovy.

Grails 2.5.0 Bootstrap.groovy:

Date.metaClass.toString = {
    return delegate.format("MM/dd/yyyy HH:mm")
}

index.gsp:

<ul>
    <li>new Date().toString() == ${new Date().toString()}</li>
    <li>new Date() == ${new Date()}</li>
    <li>new Date() as String == ${new Date() as String}</li>
</ul>

/*Output:
new Date().toString() == 06/15/2015 10:32
new Date() == Mon Jun 15 10:32:33 EDT 2015
new Date() as String == Mon Jun 15 10:32:33 EDT 2015
*/

groovyConsole Groovy 2.4.3 /:

Date.metaClass.toString = {
    return delegate.format("MM/dd/yyyy HH:mm")
}

println(new Date())
println(new Date() as String)
println(new Date().toString())

/*Output:
06/15/2015 10:38
Mon Jun 15 10:38:12 EDT 2015
Mon Jun 15 10:38:12 EDT 2015
*/

, Groovy, toString() , - -.

+4
3

- , new Date(), , , Java toString() , Groovy , asType() toString(). , , , ElasticSearch.

0

, Groovy, , grails console, ? BootStrap , run-app . toString , , .

+2

Just think about " as String" .. if you override the method asType:

Date.metaClass.asType = { Class clazz ->
 return "Hello"
}

(new Date()) as String
===> Hello

but still:

new Date()
===> Wed Jul 01 20:12:35 EEST 2015
+1
source

All Articles