java.util.Date:七天前 [英] java.util.Date: seven days ago
问题描述
我在Jasper Reports中创建了一个报告,它只识别java.util.Date(不是Calendar或Gregorian等)。
I have a report created in Jasper Reports which ONLY recognizes java.util.Date's (not Calendar or Gregorian, etc).
有没有办法创建一个当前日期前7天的日期?
Is there a way to create a date 7 days prior to the current date?
理想情况下,它看起来像这样:
Ideally, it would look something like this:
new Date(New Date() - 7)
更新:我可以不要强调这一点:JasperReports不能识别Java Calendar对象。
UPDATE: I can't emphasize this enough: JasperReports DOES NOT RECOGNIZE Java Calendar objects.
推荐答案
从现在开始:
long DAY_IN_MS = 1000 * 60 * 60 * 24;
new Date(System.currentTimeMillis() - (7 * DAY_IN_MS))
来自任意日期日期
:
new Date(date.getTime() - (7 * DAY_IN_MS))
编辑:正如其他答案中所指出的,不是帐户对于夏令时,如果这是一个因素。
只是为了澄清我所说的限制:
Just to clarify that limitation I was talking about:
对于受夏令时影响的人 ,如果提前7天
,则表示如果正确现在是 2010年3月14日中午12点
,您希望在7天之前计算
以产生 2010年3月7日中午12点
,请注意。
For people affected by daylight savings time, if by 7 days earlier
, you mean that if right now is 12pm noon on 14 Mar 2010
, you want the calculation of 7 days earlier
to result in 12pm on 7 Mar 2010
, then be careful.
此解决方案准确地找到24小时* 7天= 168小时之前的日期/时间。
This solution finds the date/time exactly 24 hours * 7 days= 168 hours earlier.
但是,有些人感到惊讶当这个解决方案发现时,例如,(2010年3月14日下午1:00) - 7 * DAY_IN_MS
可能 在(2010年3月7日中午12:00)
中返回结果 挂钟时间在您的时区 在2个日期/时间之间不一样( 1pm
vs 12pm
) 。这是因为当晚开始或结束的夏令时以及挂钟时间丢失或获得一小时。
However, some people are surprised when this solution finds that, for example, (14 Mar 2010 1:00pm) - 7 * DAY_IN_MS
may return a result in(7 Mar 2010 12:00pm)
where the wall-clock time in your timezone isn't the same between the 2 date/times (1pm
vs 12pm
). This is due to daylight savings time starting or ending that night and the "wall-clock time" losing or gaining an hour.
如果DST不是您的一个因素或者如果你确实想要(168小时)
,无论挂钟时间如何变化,那么这个解决方案都能正常工作。
If DST isn't a factor for you or if you really do want (168 hours)
exactly (regardless of the shift in wall-clock time), then this solution works fine.
否则,你可能需要赔偿你的 7天前
并不真正意味着168小时(由于DST开始或结束时间)时间表。)
Otherwise, you may need to compensate for when your 7 days earlier
doesn't really mean exactly 168 hours (due to DST starting or ending within that timeframe).
这篇关于java.util.Date:七天前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!