Groovy web console

subscribe to the feed Subscribe
to this
site
clearTime Sample With clone() to Preserve Original Value (via #groovywebconsole)
tweet this snippet Tweet
this
script

clearTime Sample With clone() to Preserve Original Value

Published 3 months ago by Stuart Fraser with tags clone() date extension clearTime()
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
TimeAndDate = Date.parse( 'MM/dd/yyyy HH:mm:ss.SSS', '11/30/2018 23:53:59.789' )

// I want a second date with no time
// WARNING: clear time impacts the original instance as well as returns it

// Correct way is to clone the date to preserve the original date value
DateOnly = TimeAndDate.clone().clearTime()

// Are things as we expet? Yes. Clone protected the original date
assert DateOnly.format( 'MM/dd/yyyy HH:mm:ss.SSS' ) == '11/30/2018 00:00:00.000'
assert TimeAndDate.format( 'MM/dd/yyyy HH:mm:ss.SSS' ) == '11/30/2018 23:53:59.789'

// ERROR
DateOnly = TimeAndDate.clearTime()

// Are things as we expet? No. We lost the time on the original instance
assert DateOnly.format( 'MM/dd/yyyy HH:mm:ss.SSS' ) == '11/30/2018 00:00:00.000'
assert TimeAndDate.format( 'MM/dd/yyyy HH:mm:ss.SSS' ) == '11/30/2018 23:53:59.789'