简体   繁体   中英

change a list of day , month and year to DATE in java

i have these lists

   def day   =[1,1,1,1,1,1,1,1,1,1,1,1,1]
   def month =[10,9,8,7,6,5,4,3,2,1,12,11]
   def year  =[2011,2011,2010,2011,2011,2012,2011]

Now i want to do some thing like this for the whole list in a kind of for loop

          def date= new Date(year,month,day)       

How can i do this

Thanks

Try not to use separate collections when the data is tightly-coupled (better yet to use an object).

dateNums = [
    [1, 10, 2011],
    [1, 9, 2011],
    // etc.
]
dates = []

dateNums.each {
    d = new Date(it[2]-1900, it[1]-1, it[0])
    println d
    dates.add(d)
}

Note that the Date(year, month, date) is deprecated, and you should likely use the Date construction methods I linked to in your previous question.

d = new Date().parse('MM/dd/yyyy', "${it[0]}/${it[1]}/${it[2]}")

Better still, skip the intermediate steps.

def getDate(month, day, year) {
    new Date().parse('MM/dd/yyyy', "${month}/${day}/${year}")
}

dates = [
    getDate(1, 10, 2011),
    getDate(1, 9, 2011)
]

dates.each { println it }

This should work as well:

def dates = [day,month,year].transpose().collect { d, m, y ->
  new Date().parse( 'dd/MM/yyyy', "$d/$m/$y" )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM