一天的第一刻
answer by ngeek 是正确的,但未能将时间放在一天的第一刻。要调整时间,请向withTimeAtStartOfDay 添加呼叫。
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
System.out.println( "startOfThisMonth: " + startOfThisMonth );
System.out.println( "startofNextMonth: " + startofNextMonth );
在美国西雅图跑步时……
startOfThisMonth: 2013-11-01T00:00:00.000-07:00
startofNextMonth: 2013-12-01T00:00:00.000-08:00
注意这两行控制台输出的区别:-7 与 -8 因为Daylight Saving Time。
通常应该始终指定时区,而不是依赖默认值。为简单起见,此处省略。应该像这样添加一行,并将时区对象传递给上面示例中使用的构造函数。
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
// UTC time zone (no offset) has a constant, so no need to construct: org.joda.time.DateTimeZone.UTC
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
java.time
以上内容正确但已过时。 Joda-Time 库现在被 Java 8 及更高版本中内置的 java.time 框架所取代。
LocalDate 表示没有时间和时区的仅日期值。时区对于确定日期至关重要。对于任何特定时刻,日期都会因全球区域而异。
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
使用其中一个TemporalAdjusters 来获取月份的第一天。
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate 可以生成一个ZonedDateTime,代表一天中的第一刻。
ZonedDateTime firstMomentOfCurrentMonth = firstOfMonth.atStartOfDay( zoneId );