Get n days before now

本文介绍了一种使用毫秒计算日期偏移的方法,通过将时间转换为自1970年1月1日以来的毫秒数,可以轻松地进行日期计算,特别是对于大范围的日期操作更为有效。
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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值