Get n days before now

peterchen-easyli發表於2012-08-23
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

相關文章