My input string date is as below:
String date = "1/13/2012";
I am getting the month as below:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = dateFormat.parse(date);
String month = new SimpleDateFormat("MM").format(convertedDate);
But how do I get the last calendar day of the month in a given String date?
E.g.: for a String "1/13/2012"
the output must be "1/31/2012"
.
You can use the following code to get last day of the month
public static String getLastDayOfTheMonth(String date) {
String lastDayOfTheMonth = "";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try{
java.util.Date dt= formatter.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
java.util.Date lastDay = calendar.getTime();
lastDayOfTheMonth = formatter.format(lastDay);
} catch (ParseException e) {
e.printStackTrace();
}
return lastDayOfTheMonth;
}
Java 8 and above:
import java.time.LocalDate;
import java.time.Year;
static int lastDayOfMonth(int Y, int M) {
return LocalDate.of(Y, M, 1).getMonth().length(Year.of(Y).isLeap());
}
subject to Basil Bourque's comment
import java.time.YearMonth;
int lastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();
YearMonth // Represent the year and month, without a date and without a time zone.
.from( // Extract the year and month from a `LocalDate` (a year-month-day).
LocalDate // Represent a date without a time-of-day and without a time zone.
.parse( // Get a date from an input string.
"1/13/2012" , // Poor choice of format for a date. Educate the source of your data about the standard ISO 8601 formats to be used when exchanging date-time values as text.
DateTimeFormatter.ofPattern( "M/d/uuuu" ) // Specify a formatting pattern by which to parse the input string.
) // Returns a `LocalDate` object.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determines the last day of the month for that particular year-month, and returns a `LocalDate` object.
.toString() // Generate text representing the value of that `LocalDate` object using standard ISO 8601 format.
See this code run live at IdeOne.com.
2012-01-31
YearMonth
The YearMonth
class makes this easy. The atEndOfMonth
method returns a LocalDate
. Leap year in February is accounted for.
First define a formatting pattern to match your string input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu" ) ;
Use that formatter to get a LocalDate
from the string input.
String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
Then extract a YearMonth
object.
YearMonth ym = YearMonth.from( ld ) ;
Ask that YearMonth
to determine the last day of its month in that year, accounting for Leap Year in February.
LocalDate endOfMonth = ym.atEndOfMonth() ;
Generate text representing that date, in standard ISO 8601 format.
String output = endOfMonth.toString() ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
The simplest way is to construt a new GregorianCalendar
instance, see below:
Calendar cal = new GregorianCalendar(2013, 5, 0);
Date date = cal.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date : " + sdf.format(date));
Output:
Date : 2013-05-31
Attention:
month the value used to set the MONTH calendar field in the calendar. Month value is 0-based e.g. 0 for January.
I use this one-liner on my JasperServer Reports:
new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyy-MM-dd").parse(new java.util.Date().format('yyyy') + "-" + (new Integer (new SimpleDateFormat("MM").format(new Date()))+1) + "-01")-1)
Doesn't look nice but works for me. Basically it's adding 1 to the current month, get the first day of that month and subtract one day.
This looks like your needs:
http://obscuredclarity.blogspot.de/2010/08/get-last-day-of-month-date-object-in.html
code:
import java.text.DateFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//Java 1.4+ Compatible
//
// The following example code demonstrates how to get
// a Date object representing the last day of the month
// relative to a given Date object.
public class GetLastDayOfMonth {
public static void main(String[] args) {
Date today = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(today);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today : " + sdf.format(today));
System.out.println("Last Day of Month: " + sdf.format(lastDayOfMonth));
}
}
Output:
Today : 2010-08-03
Last Day of Month: 2010-08-31
public static String getLastDayOfMonth(int year, int month) throws Exception{
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date lastDayOfMonth = calendar.getTime();
return sdf.format(lastDayOfMonth);
}
public static void main(String[] args) throws Exception{
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 4));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 5));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 6));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 7));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 8));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 9));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 10));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 11));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 12));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 1));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 3));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2010, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2011, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2012, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2013, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2014, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2015, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2016, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2017, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2018, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2019, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2020, 2));
System.out.println("Last Day of Month: " + getLastDayOfMonth(2021, 2));
}
output:
Last Day of Month: 2017-01-31
Last Day of Month: 2017-02-28
Last Day of Month: 2017-03-31
Last Day of Month: 2017-04-30
Last Day of Month: 2017-05-31
Last Day of Month: 2017-06-30
Last Day of Month: 2017-07-31
Last Day of Month: 2017-08-31
Last Day of Month: 2017-09-30
Last Day of Month: 2017-10-31
Last Day of Month: 2017-11-30
Last Day of Month: 2017-12-31
Last Day of Month: 2018-01-31
Last Day of Month: 2018-02-28
Last Day of Month: 2018-03-31
Last Day of Month: 2010-02-28
Last Day of Month: 2011-02-28
Last Day of Month: 2012-02-29
Last Day of Month: 2013-02-28
Last Day of Month: 2014-02-28
Last Day of Month: 2015-02-28
Last Day of Month: 2016-02-29
Last Day of Month: 2017-02-28
Last Day of Month: 2018-02-28
Last Day of Month: 2019-02-28
Last Day of Month: 2020-02-29
Last Day of Month: 2021-02-28
Works fine for me with this
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone());
cal.set(Calendar.MONTH, month-1);
cal.set(Calendar.YEAR, year);
cal.add(Calendar.DATE, -1);
cal.set(Calendar.DAY_OF_MONTH,
cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTimeInMillis();
With Java 8
DateTime
/LocalDateTime
:
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
ValueRange range = date.range(ChronoField.DAY_OF_MONTH);
Long max = range.getMaximum();
LocalDate newDate = date.withDayOfMonth(max.intValue());
System.out.println(newDate);
OR
String dateString = "01/13/2012";
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US);
LocalDate date = LocalDate.parse(dateString, dateFormat);
LocalDate newDate = date.withDayOfMonth(date.getMonth().length(date.isLeapYear()));
System.out.println(newDate);
Output:
2012-01-31
LocalDateTime
should be used instead ofLocalDate
if you have time information in your date string . I.E.2015/07/22 16:49
By using java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
.with(TemporalAdjusters.lastDayOfMonth());
Use GregorianCalendar
. Set the date of the object, and then use getActualMaximum(Calendar.DAY_IN_MONTH)
.
http://docs.oracle.com/javase/7/docs/api/java/util/GregorianCalendar.html#getActualMaximum%28int%29 (but it was the same in Java 1.4)
String givenStringDate ="07/16/2020";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
java.util.Date convertedUtillDate;
/*
* If your output requirement is in LocalDate format use below snippet
*
*/
LocalDate localDate =LocalDate.parse(givenStringDate, formatter);
LocalDate localDateLastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
/*
* If your output requirement is in Calendar format use below snippet
*
*/
convertedUtillDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
Calendar calendarLastDayOfMonth = Calendar.getInstance();
calendarLastDayOfMonth.setTime(convertedUtillDate);
int lastDate = calendarLastDayOfMonth.getActualMaximum(Calendar.DATE);
calendarLastDayOfMonth.set(Calendar.DATE, lastDate);
Tested in Java 1.8. I hope this will help some one.
You can make use of the plusMonths and minusDays methods in Java 8:
// Parse your date into a LocalDate
LocalDate parsed = LocalDate.parse("1/13/2012", DateTimeFormatter.ofPattern("M/d/yyyy"));
// We only care about its year and month, set the date to first date of that month
LocalDate localDate = LocalDate.of(parsed.getYear(), parsed.getMonth(), 1);
// Add one month, subtract one day
System.out.println(localDate.plusMonths(1).minusDays(1)); // 2012-01-31
Source: Stackoverflow.com