I have two timestamps: start/end of period (calendar month, week or day).
I need to calculate previous period (previous month, week etc.). I tried to do it using LocalDateTime
functions. E.g. using getMonthOfYear() - 1
for month period but what to do with last day (beforeDayTo)?
E.g. september's getDayOfMonth()
returns 30, but for previous period (august) I need 31 etc.
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));
How to solve this issue?
You are getting the number of Day of the current month.
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();
The last line give you the timestanp as a Long. So you can do it :
Timestamp timestamp = new Timestamp(cal.getTimeInMillis());
Calendar alow you to do all what you want to do. Take a look to this http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html