如何获取给定日期的月份的最后一天 [英] How to get last day of the month for the given date

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

问题描述

我有一个给定的日期:

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

日历c = c.getInstance();

c.setTime(date);

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

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




预期输出:01/31/2017



原始输出:02/01/2017


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



任何人都可以帮助我吗?

解决方案

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆