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

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

本文介绍了如何获取给定日期的月份的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个给定的日期:

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

日历c = c.getInstance();

c.setTime(date);

现在指向一个月的最后一天,我使用以下代码:

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



我没有得到预期的输出。它让我回到下个月的第一天。



任何人都可以帮助我吗?

解决方案

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

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.

这篇关于如何获取给定日期的月份的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 16:53