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
Share:
12,825
blaughli
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, 2022

Comments

  • blaughli
    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
    blaughli over 12 years
    Thanks, I'm close. Printing yourdate spits out a very long string, which I assume is the output of GregorianCalendar. 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 want yourdate to print as 2010-10-01
  • tolitius
    tolitius over 12 years
    that is how it prints ( try print String.format('%tY-%<tm-%<td', yourDate) ), I added an example
  • blaughli
    blaughli over 12 years
    I want to use yourDate in the script shown in the question. I want to be able to do : yourDate + it.months
  • blaughli
    blaughli over 12 years
    Also, what if I want yourDate to be the current date, in the same format yyyy-mm-dd?
  • blaughli
    blaughli over 12 years
    Thank you so much tolitius :)
  • blaughli
    blaughli over 12 years
    One final question - Calendar.instance returns 2011-11-03. How would I make it always return "01" in the "days" value? i.e. 01 instead of 03
  • tolitius
    tolitius over 12 years
    yourDate.set( Calendar.DAY_OF_MONTH, 1 )
  • blaughli
    blaughli over 12 years
    Well that pretty much does it. I wish you happiness and success.