tl;博士
LocalDate // Represent a date-only value without a time-of-day and without a time zone.
.now( // Determine the current date as seen through the wall-clock time used by people in certain region (a time zone).
ZoneId.of( "America/Montreal" ) // Real time zone names have names in the format of `Continent/Region`. Never use 2-4 letter pseudo-zones such as `IST`, `PST`, or `CST`, which are neither standardized nor unique.
) // Return a `LocalDate`.
.with( // Move from one date another by passing a `TemporalAdjuster` implementation.
TemporalAdjusters // Class providing several implementations of `TemporalAdjuster`.
.firstDayOfNextMonth() // This adjuster finds the date of the first of next month, as its name suggests.
) // Returns another `LocalDate` object. The original `LocalDate` object is unaltered.
.toString() // Generate text in standard ISO 8601 format of YYYY-MM-DD.
看到这个code run live at IdeOne.com。
2020-02-01
详情
您正在使用糟糕的日期时间类,几年前一致通过定义 java.time 类的JSR 310 使这些类过时。
Answer by deHaar 是正确的。这是一个更短的解决方案。
TemporalAdjuster
为了从一个日期移动到另一个日期,java.time 类包括TemporalAdjuster 接口。将这些对象之一传递给许多其他 java.time 类中的with 方法。
TemporalAdjusters.firstDayOfNextMonth()
在类TemporalAdjusters 中可以找到该接口的几个实现(注意s 的复数形式)。其中之一是firstDayOfNextMonth(),正是您所需要的。
获取今天的日期。时区是必需的,因为对于任何给定的时刻,日期在全球范围内因时区而异。如果省略,则隐式应用 JVM 的当前默认时区。最好是明确的。
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
LocalDate today = LocalDate.now( z ) ;
获取您的 TemporalAdjuster 对象。
TemporalAdjuster ta = TemporalAdjusters.firstDayOfNextMonth() ;
应用该调整器以获取另一个 LocalDate 对象。请注意,java.time 类在设计上是不可变的。所以我们得到一个新对象而不是改变原来的对象。
LocalDate firstOfNextMonth = today.with( ta ) ;
如果需要,我们可以将此代码缩短为单行代码。
LocalDate firstOfNextMonth =
LocalDate
.now(
ZoneId.of( "Africa/Tunis" )
)
.with(
TemporalAdjusters.firstDayOfNextMonth()
)
;
文字
您想要的 YYYY-MM-DD 输出格式符合解析/生成文本时 java.time 类默认使用的ISO 8601 标准。所以不需要指定格式化模式。
String output = firstOfNextMonth.toString() ;
2020-02-01
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?
ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如Interval、YearWeek、YearQuarter 和more。