tl;博士
YearMonth // Represent a year-month without day-of-month.
.now( // Capture the current year-month as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Africa/Tunis" ) // Specify your desired time zone. Never use 3-4 letter pseudo-zones such as `CET`.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determine the last day of this year-month. Returns a `LocalDate` object.
.atStartOfDay( // Let java.time determine the first moment of the day. Not necessarily 00:00:00, could be 01:00:00 or some other time-of-day because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object, representing a date, a time-of-day, and a time zone.
java.time
您正在使用多年前已被取代的糟糕的旧 Calendar 类,而是现代的 java.time 类。
LocalDate
如果您只需要日期,请使用LocalDate 类。那么时区与您的输出无关。
但时区对于确定当前日期非常重要。对于任何给定的时刻,日期在全球各地都因地区而异。
以continent/region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 3-4 个字母的缩写,例如 CET 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "Europe/Paris" ) ; // Or "Africa/Tunis" etc.
LocalDate today = LocalDate.now( z ) ; // Capture the current date as seen by the wall-clock time used by the people of a certain region (a time zone).
YearMonth
获取该日期的月份。用YearMonth 表示一年一个月。
YearMonth ym = YearMonth.from( today ) ;
或者跳过LocalDate。
YearMonth ym = YearMonth.now( z ) ;
获取月底。
LocalDate endOfThisMonth = ym.atEndOfMonth() ;
ISO 8601
要生成代表LocalDate 对象值的String,请调用toString。默认格式取自ISO 8601 标准。对于将是 YYYY-MM-DD 的仅日期值,例如 2018-01-23。
String output = endOfThisMonth.toString() ;
如果您需要其他格式,请使用DateTimeFormatter 类。在 Stack Overflow 上搜索许多示例和讨论。
时刻
如果您需要一点时间,可以将时间和时区添加到您的 LocalDate 以获取 ZonedDateTime。或者让ZonedDateTime 确定一天中的第一个时刻(不始终是 00:00:00!)。
ZonedDateTime zdt = LocalDate.atStartOfDay( z ) ;
关于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。