How to change Groovy Date format
12,825
In order to parse it out from a String:
Date.parse( "yyyy-M-d", "2010-10-01" )
In order to format the date that you already have:
def yourDate= new GregorianCalendar( 2010, Calendar.OCTOBER, 1 )
assert String.format('%tY-%<tm-%<td', yourDate) == '2010-10-01'
EDIT (to answer the comment)
groovy:000> yourDate= new GregorianCalendar( 2010, Calendar.OCTOBER, 1 )
===> java.util.GregorianCalendar[...]
groovy:000> print String.format('%tY-%<tm-%<td', yourDate)
2010-10-01===> null
groovy:000>
and backwards:
groovy:000> Date.parse( "yyyy-M-d", String.format('%tY-%<tm-%<td', yourDate) )
===> Fri Oct 01 00:00:00 EDT 2010
current date:
groovy:000> yourDate = Calendar.instance
===> java.util.GregorianCalendar[..]
groovy:000> print String.format('%tY-%<tm-%<td', yourDate)
2011-11-03===> null
Author by
blaughli
Trying to learn how to code. Actually trying to understand computer science. I love science - physics, chemistry, math, hopefully biology if I get there. I want to combine my interests into an awesome career, something like oceanography. There must be cool jobs for a surfer out there that use science and CS skills!
Updated on June 04, 2022Comments
-
blaughli almost 2 years
I want to get my dates into a format like this:
2010-10-01
How do I do this?
Also, I grabbed this from another question:
use (groovy.time.TimeCategory) {
Date date = Date.parse("dd-MMM-yyyy", "15-Mar-2011") def months = (0..11).collect { (date + it.months).format("MMM/yyyy") }
}
How would I change the output of this script to the format I specified above? Thanks:)
-
blaughli over 12 yearsThanks, I'm close. Printing
yourdate
spits out a very long string, which I assume is the output ofGregorianCalendar
. How do I get a variable out of this that only has the date as a value, in the format I want? i.e. I wantyourdate
to print as2010-10-01
-
tolitius over 12 yearsthat is how it prints ( try print String.format('%tY-%<tm-%<td', yourDate) ), I added an example
-
blaughli over 12 yearsI want to use
yourDate
in the script shown in the question. I want to be able to do :yourDate + it.months
-
blaughli over 12 yearsAlso, what if I want
yourDate
to be the current date, in the same formatyyyy-mm-dd
? -
blaughli over 12 yearsThank you so much tolitius :)
-
blaughli over 12 yearsOne final question - Calendar.instance returns 2011-11-03. How would I make it always return "01" in the "days" value? i.e.
01
instead of03
-
tolitius over 12 yearsyourDate.set( Calendar.DAY_OF_MONTH, 1 )
-
blaughli over 12 yearsWell that pretty much does it. I wish you happiness and success.