How to compare two string dates in Java?

Convert them to an actual Date object, then call before. SimpleDateFormat sdf = new SimpleDateFormat(“yyyy/MM/dd h:m”); System.out.println(sdf.parse(startDate).before(sdf.parse(endDate))); Recall that parse will throw a ParseException, so you should either catch it in this code block, or declare it to be thrown as part of your method signature.

java: how to mock Calendar.getInstance()?

You can mock it using PowerMock in combination with Mockito: On top of your class: @RunWith(PowerMockRunner.class) @PrepareForTest({ClassThatCallsTheCalendar.class}) The key to success is that you have to put the class where you use Calendar in PrepareForTest instead of Calendar itself because it is a system class. (I personally had to search a lot before I found … Read more

First day of next month with java Joda-Time

LocalDate today = new LocalDate(); LocalDate d1 = today.plusMonths(1).withDayOfMonth(1); A little easier and cleaner, isn’t it? 🙂 Update: If you want to return a date: return new Date(d1.toDateTimeAtStartOfDay().getMillis()); but I strongly advise you to avoid mixing pure DATE types (i.e. a day in the calendar, without time information) with DATETIME types, specially with a “physical” … Read more

How to get last month/year in java?

Your solution is here but instead of addition you need to use subtraction c.add(Calendar.MONTH, -1); Then you can call getter on the Calendar to acquire proper fields int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero int year = c.get(Calendar.YEAR);

Date object to Calendar [Java]

What you could do is creating an instance of a GregorianCalendar and then set the Date as a start time: Date date; Calendar myCal = new GregorianCalendar(); myCal.setTime(date); However, another approach is to not use Date at all. You could use an approach like this: private Calendar startTime; private long duration; private long startNanos; //Nano-second … Read more