如何实现打印当前日期及往前推7天的日期
打印当前日期及往前偏移7天的日期
以下是基于Groovy的实现方案,可直接输出当前日期和往前偏移7天的日期:
// 定义函数,传入偏移天数返回对应日期字符串 def getOffsetDate(int days) { def currentDate = new Date() currentDate.setDate(currentDate.getDate() - days) return currentDate.toString() } // 打印当前日期 println "当前日期:${new Date().toString()}" // 打印往前推7天的日期 println "往前偏移7天的日期:${getOffsetDate(7)}"
代码说明
new Date():实例化当前时间的日期对象setDate()方法:调整日期对象的日数值,减去指定天数即可得到往前偏移的日期- 直接调用
new Date().toString()可获取当前日期的字符串格式,调用getOffsetDate(7)则得到7天前的日期
内容的提问来源于stack exchange,提问作者Goofy
相关产品推荐
相关产品推荐

