3

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());
Rthp
  • 85
  • 1
  • 13
  • What is it about DateUtils that you find compelling? Yes, Calendar is awkward to use, but you already have a working solution and can easily convert a Calendar into a Date. – micker Jun 07 '16 at 19:32
  • Ya I just wanted to use DateUtils. But I found out DateUtils internally uses Calendar. So ended up using Calendar anyways. – Rthp Jun 09 '16 at 15:51

2 Answers2

3

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
Hesham Ahmed
  • 207
  • 1
  • 4
  • Gives me error for last line: `The method ceiling(Date, int) is undefined for the type DateUtils` – Rthp Jun 07 '16 at 19:50
  • Make sure you're using the latest DateUtils. If using maven then add the following to your pom.xml org.apache.commons commons-lang3 3.4 – Hesham Ahmed Jun 07 '16 at 20:04
0

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);
Rthp
  • 85
  • 1
  • 13