在groovy中减去1或2的日期

abi*_*964 11 java groovy

我需要通过从MM/dd/yyyy格式中减去当前日期的数字来获取日期

我通过使用获得了当前日期 new Date().format("MM/dd/yyyy")

请帮我一个功能,减去上述日期1,2并以MM/dd/yyyy格式生成日期

我试过了

def today = new Date().format("MM/dd/yyyy")
def yesterday = today -1
println today
println yesterday
Run Code Online (Sandbox Code Playgroud)

这给了我

01/11/2012
0/11/2012
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 22

您正在从字符串中减去

尝试:

def today = new Date()
def yesterday = today - 1
println today.format("MM/dd/yyyy")
println yesterday.format("MM/dd/yyyy")
Run Code Online (Sandbox Code Playgroud)


Peg*_*ggs 9

Groovy附带了一些非常有用的方法来操作日期,你可以使用前一天的.previous()和后一天的.next().

def today = new Date()
def yesterday = today.previous()
println today.format("MM/dd/yyyy")
println yesterday.format("MM/dd/yyyy")
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助