【问题标题】:Calculate previous calendar period计算上一个日历期间
【发布时间】:2015-09-09 11:24:22
【问题描述】:

我有两个时间戳:期间的开始/结束(日历月、周或日)。

我需要计算上一个时期(上个月、上一周等)。我尝试使用LocalDateTime 函数来做到这一点。例如。使用getMonthOfYear() - 1 表示月份,但最后一天(beforeDayTo)怎么办?

例如9 月的 getDayOfMonth() 返回 30,但上一期(8 月)我需要 31 等。

Long fromDateMillis = 1440277200000L;
Long toDateMillis = 1440363599000L;

LocalDateTime fromLocalDate = new LocalDateTime(fromDateMillis);
LocalDateTime toLocalDate = new LocalDateTime(toDateMillis)

int beforeYear = fromLocalDate.getYear();
int beforeMonthFrom = fromLocalDate.getMonthOfYear() - 1;
int beforeMonthTo = toLocalDate.getMonthOfYear() - 1;
int beforeDayFrom = fromLocalDate.getDayOfMonth();
int beforeDayTo = toLocalDate.getDayOfMonth();
Timestamp prevFromDate = Timestamp
        .valueOf(java.time.LocalDateTime.of(beforeYear, beforeMonthFrom, 1, 0, 0, 0));
Timestamp prevToDate = Timestamp
        .valueOf(java.time.LocalDateTime.of(beforeYear, beforeMonthTo, beforeDayTo, 0, 0, 0));

如何解决这个问题?

【问题讨论】:

  • 目前尚不清楚您的预期输出是什么以及您得到什么。 minimal reproducible example
  • @Lay`O 请说出您的期望和得到的结果?
  • @Dante我预计上一个时期是 01.08.2015 - 31.08.2015 但会得到 01.08.2015 - 30.08.2015

标签: java date datetime time timestamp


【解决方案1】:

您正在获取当前月份的天数。

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.getTimeInMillis();

最后一行给你一个 Long 的 timestanp。所以你可以做到:

Timestamp timestamp = new Timestamp(cal.getTimeInMillis());

日历让你做所有你想做的事。 看看这个http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多