Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a date by 1 or 2 in groovy

Tags:

java

groovy

I need to get a date by subtracting a number from current date in MM/dd/yyyy format

I got the current date by using new Date().format("MM/dd/yyyy")

Please help me with a function that subtracts 1,2 to the above date and produces a date in MM/dd/yyyy format

I have tried

def today = new Date().format("MM/dd/yyyy")
def yesterday = today -1
println today
println yesterday

which gives me

01/11/2012
0/11/2012
like image 970
AabinGunz Avatar asked Jan 11 '12 09:01

AabinGunz


People also ask

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I convert a date to a string in Groovy?

String newDate = Date. parse('MM/dd/yyyy',dt). format("yyyy-MM-dd'T'HH:mm:ss'Z'");


2 Answers

You are subtracting from a String

try:

def today = new Date()
def yesterday = today - 1
println today.format("MM/dd/yyyy")
println yesterday.format("MM/dd/yyyy")
like image 159
tim_yates Avatar answered Sep 16 '22 14:09

tim_yates


Groovy comes with some really useful methods for manipulating dates you can use .previous() for the day before and .next() for the day after.

def today = new Date()
def yesterday = today.previous()
println today.format("MM/dd/yyyy")
println yesterday.format("MM/dd/yyyy")

Hope this helps

like image 26
Peggs Avatar answered Sep 19 '22 14:09

Peggs