java - 上个月的开始日期

时间:2012-09-13 01:30:35

标签: java date calendar

我想计算上个月的开始日期。我已经提到了this post,我写了如下代码:

Calendar calendar = getCalendar(new Date());
calendar.set(Calendar.DAY_OF_MONTH-1,
        calendar.getActualMinimum(DAY_OF_MONTH));
calendar = getTimeToBeginningOfDay(calendar);

return calendar.getTime();

通过这个,我可以在上个月结束前获得日期。帮助我获取任何帮助的开始日期。

3 个答案:

答案 0 :(得分:1)

您可能会得到您的期望:

Calendar c = Calendar.getInstance();

// substract one month
c.add(Calendar.MONTH, -1);

// get to the lowest day of that month
c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));

// lowest possible time in that day
c.set(Calendar.HOUR_OF_DAY, c.getActualMinimum(Calendar.HOUR_OF_DAY));
c.set(Calendar.MINUTE, c.getActualMinimum(Calendar.MINUTE));
c.set(Calendar.SECOND, c.getActualMinimum(Calendar.SECOND));

答案 1 :(得分:1)

你永远不应该对Calendar.DAY_OF_MONTH等字段常量进行数学运算。你想要做的是:

Calendar calendar = getCalendar(new Date());
calendar.add(Calendar.MONTH, -1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar = getTimeToBeginningOfDay(calendar);

return calendar.getTime();

答案 2 :(得分:1)

如果您只想要上个月的第一天,那么应该这样做。

    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.MONTH, -1);
    instance.set(Calendar.DAY_OF_MONTH, 1);

    System.out.println(instance.getTime());

如果您需要清除时间组件,请使用帖子中提到的getTimeToBeginningOfDay()来实现此目的。