Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last day of the month for the given date [duplicate]

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?

like image 814
Tansheet Izhad Avatar asked Jan 17 '17 12:01

Tansheet Izhad


People also ask

How do you find the first and last day of the current month?

To get the first and last day of the current month, use the getFullYear() and getMonth() methods to get the current year and month and pass them to the Date() constructor to get an object representing the two dates. Copied! const now = new Date(); const firstDay = new Date(now.

How do I get the last day of the month in Python?

Method #1 : Using replace() + timedelta() In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month.

How do I find the last day of the month LocalDate?

The atEndOfMonth() method of YearMonth class in Java is used to return a LocalDate of the last day of month based on this YearMonth object with which it is used.


2 Answers

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.

like image 174
GhostCat Avatar answered Oct 08 '22 07:10

GhostCat


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

like image 39
Evgeniy Dorofeev Avatar answered Oct 08 '22 09:10

Evgeniy Dorofeev