How to get last day of the month for the given dat

2020-07-17 06:33发布

I have a given date:

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

Calendar c = c.getInstance();

c.setTime(date);

Now to point to the last day of the month I am using the following code:

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

Expected Output : 01/31/2017

Original Output : 02/01/2017

I am not getting the expected output. Its returning me the first day of next month.

Can anyone please help me?

2条回答
闹够了就滚
2楼-- · 2020-07-17 06:58

I have doubts about mm/dd/yyyy. Try this

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());

it gives expected date:

Tue Jan 31 00:00:00 EET 2017

查看更多
▲ chillily
3楼-- · 2020-07-17 07:08

You better use the new date time features of Java 8 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, you could theoretically also use Calendar objects and do all kinds of low level operations yourself. But chances are: you will get that wrong ... well, unless you look here and follow the advise from there.

But as Basil is correctly pointing out: The 310 project is pretty close to java.time (because the later was designed to match the former); and 310 can be "ported" back to Java7. So if there is more than one place where you need to deal with dates, I would look into exactly that: making your life easier by using the "sane" date/time library.

查看更多
登录 后发表回答