I'm trying to convert two dates into this pattern: yyyy-MM-dd HH:mm:ss.SSS.
I need to retrieve two dates:
- Last year, same month, day 1, 00:00:00.000
- Last day of previous month, 23:59:59.999
So, as of today, I need these two values:
2022-11-01 00:00:00.0002023-10-31 23:59:59.999
The problem is: I get 2022-11-01 12:00:00.000.
This is the code that generates last year's date.
private String getLastYear() {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.YEAR, -1);
c.set(Calendar.DAY_OF_MONTH, 1);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return format.format(c.getTime());
}
If I try adding one hour, the output will be: 2022-11-01 13:00:00.000.
Also, I can't retrieve the last day of the previous month. As I have read here, all I keep getting is the first day of the next month.
Here's the code.
private String getPreviousMonth() {
DateFormat format = new SimpleDateFormat(DATE_PATTERN);
Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
c.add(Calendar.MONTH, -1);
c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
c.set(Calendar.HOUR, 23);
c.set(Calendar.MINUTE, 59);
c.set(Calendar.SECOND, 59);
c.set(Calendar.MILLISECOND, 999);
return format.format(c.getTime());
}
There is something I'm missing. Any help is highly appreciated!
You say any help is highly appreciated, so here's an example that uses
java.time, which uses today as base and calculates the two desired results as follows:First of current month in the last year
2023-11-17⇒2022-11-17)2022-11-17⇒2022-11-01)2022-11-01⇒2022-11-01 00:00:00.000)Last day of last month at the end of the day
2023-11-17⇒2023-10-17)2023-10-17⇒2023-10-31)2023-10-31⇒2023-10-31 23:59:59.999)Output (execution date 2023-11-17):