How to get the last day of the month for a given date

I have a date:

01/10/2017(mm/dd/yyyy)

Calendar c = c.getInstance();

c.setTime(date);

Now, to indicate the last day of the month, I use the following code:

c.set(Calendar.Date, c.getActualMaximum(Calendar.Date));

Expected Result: 01/31/2017

Original Release: 02/01/2017

I do not get the expected result. His return to me on the first day of the next month.

Can anybody help me?

+4
source share
2 answers

It is better to use the new Java 8 date time functions here:

LocalDate date = LocalDate.of(2000, Month.OCTOBER, 15);
LocalDate lastOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
System.out.printf("last day of Month: %s%n", lastOfMonth );

Yes, theoretically you could also use Calendar objects and do all kinds of low-level operations yourself. But there is a possibility: you will get it wrong ... well, if you do not look here and follow the advice from there.

: 310 java.time( , ); 310 "" Java7. , , , : , "" .

+8

mm/dd/yyyy.

Date d = new SimpleDateFormat("MM/dd/yyyy").parse("01/10/2017");
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.DATE, c.getActualMaximum(Calendar.DATE));
System.out.println(c.getTime());

:

31 00:00:00 EET 2017

0

Source: https://habr.com/ru/post/1667009/


All Articles