How to use Apache DateUtils to get previous month from first day to last day with time [JAVA]?

3.8k views Asked by At

If the input is today(June 7), then it should give me May 1 12:00 AM to May 31, 11:59 PM. I was using Calendar but I want to use DateUtils.

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, -1);
calendar.set(Calendar.HOUR,23);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,59);
System.out.println("Last date of month: " + calendar.getTime());


calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE,00);
calendar.set(Calendar.SECOND,00);
System.out.println("fir stdate of month: " + calendar.getTime());
2

There are 2 answers

0
Rthp On BEST ANSWER

I ended up using JodaTime. Much easier!

MutableDateTime dateTime = new MutableDateTime();
System.out.println("CurrentTime " + dateTime);
dateTime.addMonths(-1); //last Month
dateTime.setMinuteOfDay(0);
dateTime.setSecondOfMinute(0);
dateTime.setHourOfDay(12);
dateTime.setDayOfMonth(1); //first Day of last Month     
System.out.println("first Day Time " + dateTime);

dateTime.setDayOfMonth(dateTime.dayOfMonth().getMaximumValue()); //set Day to last Day of that month
dateTime.setMinuteOfDay(59);
dateTime.setSecondOfMinute(59);
dateTime.setHourOfDay(23); //time set to night time 11:59:59

System.out.println("last Day Time " + dateTime);
2
Hesham Ahmed On

DateUtils can do the required:

Date lastmonth = DateUtils.addMonths(new Date(), -1);
System.out.println(lastmonth);
System.out.println(DateUtils.truncate(lastmonth, Calendar.MONTH));
System.out.println(DateUtils.addMinutes(DateUtils.ceiling(lastmonth, Calendar.MONTH), -1));

Edit: Adding output

Sat May 07 23:06:05 AST 2016
Sun May 01 00:00:00 AST 2016
Tue May 31 23:59:00 AST 2016