计算上一个日历周期
Calculate previous calendar period
我有两个时间戳:start/end 期间(日历月、周或日)。
我需要计算上一时期(前一个月、前一周等)。我尝试使用 LocalDateTime
函数来做到这一点。例如。在月期间使用 getMonthOfYear() - 1
但如何处理最后一天 (beforeDayTo)?
例如9 月的 getDayOfMonth()
returns 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));
如何解决这个问题?
您正在获取当月的天数。
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 的时间戳。所以你可以做到:
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
日历可让您随心所欲。
看看这个http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html
我有两个时间戳:start/end 期间(日历月、周或日)。
我需要计算上一时期(前一个月、前一周等)。我尝试使用 LocalDateTime
函数来做到这一点。例如。在月期间使用 getMonthOfYear() - 1
但如何处理最后一天 (beforeDayTo)?
例如9 月的 getDayOfMonth()
returns 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));
如何解决这个问题?
您正在获取当月的天数。
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 的时间戳。所以你可以做到:
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
日历可让您随心所欲。 看看这个http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html