加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Get n days before now

发布时间:2020-12-14 16:54:24 所属栏目:大数据 来源:网络整理
导读:When I tried to google? and get a way to get a Date() n days before now. Lots of the answer are trying to do with Calendar.set() or GregorianCalendar.roll(). When n 30,enven 366,the solution becomes complex. The easier way for me is calcul
When I tried to google? and get a way to get a Date() n days before now.
Lots of the answer are trying to do with Calendar.set() or GregorianCalendar.roll().
When n > 30,enven > 366,the solution becomes complex.
The easier way for me is calculating with milliseconds since January 1,1970,00:00:00 GMT.

A groovy example:
What you have to care for this way is the value of milliseconds is large.
For example,the value of milliseconds of 50days is more than 32-bit unsiged.
But the good news is that the value of milliseconds of 100years is less than 43-bit unsigned.

import java.util.Date

def now = new Date()
def nowMsFrom1970 = now.getTime()
def days = 32
def MsInOneDay = 24*3600*1000

def days_before = now.clone()
days_before.setTime(nowMsFrom1970 - (long)days * MsInOneDay)

log.info(now.format("YYYY-MM-dd HH:mm:ss"))
log.info("Day before " + days.toString() + " days:")
log.info(days_before.format("YYYY-MM-dd HH:mm:ss"))

result: Thu Aug 23 22:38:18 CST 2012:INFO:2012-08-23 22:38:18 Thu Aug 23 22:38:18 CST 2012:INFO:Day before 32 days: Thu Aug 23 22:38:18 CST 2012:INFO:2012-07-22 22:38:18

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读