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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With