tl;dr
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 // Specify a formatting pattern by which to parse the input string.
.ofPattern( "M/d/uuuu" ) // Match the pattern of your input.
) // 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() ;
About java.time
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.
java.util.Date
andSimpleDateFormat
classes are now legacy, supplanted by the java.time classes. See Answers such as the one by Zeeshan and the one by Krishna for examples of usingLocalDate
and other modern date-time classes. – Darindaring