且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取给定日期的月份的最后一天

更新时间:2023-01-27 16:16:14

Java 8的新日期时间功能在这里:

  LocalDate date = LocalDate.of(2000,Month.OCTOBER,15); 
LocalDate lastOfMonth = date.with(TemporalAdjusters.lastDayOfMonth());
System.out.printf(月的最后一天:%s%n,lastOfMonth);是的,您理论上也可以使用Calendar对象,并自己进行各种低级操作。但是有机会:你会得到错误的...好吧,除非你看起来这里并遵循那里的建议。

但是,Basil正确地指出:310项目与java.time非常接近(因为后者的设计是为了匹配前者);和310可以移植返回到Java7。所以如果有不止一个地方需要处理日期,那么我会研究一下:通过使用理智的日期/时间库,让你的生活更轻松。


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?

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.