tl;博士
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.
看到这个code run live at IdeOne.com。
2012-01-31
YearMonth
YearMonth 类使这很容易。 atEndOfMonth 方法返回 LocalDate。闰年 2 月计算在内。
首先定义一个格式化模式来匹配你的字符串输入。
DateTimeFormatter f = DateTimeFormatter.ofPattern("M/d/uuuu");
使用该格式化程序从字符串输入中获取LocalDate。
String s = "1/13/2012" ;
LocalDate ld = LocalDate.parse( "1/13/2012" , f ) ;
然后提取一个YearMonth 对象。
YearMonth ym = YearMonth.from( ld ) ;
请YearMonth 确定当年该月的最后一天,占2 月的Leap Year。
LocalDate endOfMonth = ym.atEndOfMonth() ;
以标准 ISO 8601 格式生成表示该日期的文本。
String output = endOfMonth.toString() ;
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。