【问题标题】:how to add year or months from current date in groovy?如何在groovy中从当前日期添加年份或月份?
【发布时间】:2015-07-29 17:40:45
【问题描述】:

如何在 groovy 脚本中向当前日期添加一年?

def Format1 = "yyyy-MM-dd"
def today = new Date()
def currentDate = today.format(Format1)

示例:2015-07-29 至 2016-07-29 和 2015-07-29 至 2015-10-29。

【问题讨论】:

    标签: date time groovy


    【解决方案1】:

    使用TimeCategory

    import groovy.time.TimeCategory
    
    def acceptedFormat = "yyyy-MM-dd"
    def today = new Date() + 1
    def currentdate = today.format(acceptedFormat)
    
    use(TimeCategory) {
        def oneYear = today + 1.year
        println oneYear
    
        def ninetyDays = today + 90.days
        println ninetyDays
    }
    

    有关其工作原理的更多信息,请参阅The Groovy Pimp my Library Pattern 上的文档。简而言之,Integer 类在use 块中得到了丰富,为它提供了额外的方法,使得日期操作非常方便。

    请注意+(或plus)运算符已经可以处理常规整数,但默认情况下是加一天。 (因此,new Date() + 1 将在 24 小时内为您提供日期)

    【讨论】:

    • 谢谢。它真的很整洁,让我想做的事情变得简单快捷。
    • 如何在没有“使用”语法的情况下编写这个?需要 BaseDuration 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    • 2020-11-11
    • 1970-01-01
    • 2015-03-27
    • 2022-08-03
    • 1970-01-01
    相关资源
    最近更新 更多