Incpetor
Incpetor

Reputation: 1303

Get Last day of the Month specified in String

I have found some answers based on Calendar to get the last date of the month.

I need a function that takes a string as date 2014-04-01 (yyyy-MM-dd) format and returns the last date in the same format.

if user enters 2014-04-05 I need the function that returns 2014-04-30.

The code I am trying is here which takes the current date time but I am stuck with using the getactualmaxium point and how to use it.

        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.MONTH,0);
        cal.set(Calendar.DATE, 0);


        Date firstDateOfPreviousMonth = cal.getTime();
        System.out.println(firstDateOfPreviousMonth );
        cal.set(Calendar.DATE, cal.getActualMaximum(Calendar.DATE));
        Date lastDateOfPreviousMonth = cal.getTime();
        System.out.println(lastDateOfPreviousMonth );

Upvotes: 0

Views: 85

Answers (2)

Peter Lawrey
Peter Lawrey

Reputation: 533472

I wouldn't use Calendar if you can use JodaTime or the new JSR-310 DateTime in Java 8.

String dateStr = "2014-04-05";
LocalDate endOfMonth = LocalDate.parse(dateStr)
                                .withDayOfMonth(1).plusMonths(1).minusDays(1);
System.out.println(endOfMonth);

What you can do, is take the start of the month, add a month and subtract a day.

Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

cal.set(Calendar.DATE, 1);
cal.add(Calendar.MONTH, 1);
cal.add(Calendar.DATE, -1);
System.out.println(cal.getTime());

Upvotes: 1

Hirak
Hirak

Reputation: 3649

Check if the following code helps

 public static void main(String[] args) throws ParseException {
     String dateStr="2014-04-05";
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        cal.setTime(sdf.parse(dateStr));
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));  
        System.out.println(sdf.format(cal.getTime())); 

}

Upvotes: 2

Related Questions