在Joda-Time中,有没有办法获取一周的第一天(星期一)的日期。
例如,我想根据今天的当前日期21/01/11找出这个星期一星期一的日期
提前干杯。
编辑:我也希望找到一周结束的日期,即星期日的日期。欢呼声
答案 0 :(得分:73)
LocalDate now = new LocalDate();
System.out.println(now.withDayOfWeek(DateTimeConstants.MONDAY)); //prints 2011-01-17
System.out.println(now.withDayOfWeek(DateTimeConstants.SUNDAY)); //prints 2011-01-23
答案 1 :(得分:26)
LocalDate today = new LocalDate();
LocalDate weekStart = today.dayOfWeek().withMinimumValue();
LocalDate weekEnd = today.dayOfWeek().withMaximumValue();
会给你第一天和最后一天,即周一和周日
答案 2 :(得分:12)
另一种选择是使用roundFloorCopy。这看起来如下:
LocalDate startOfWeek = new LocalDate().weekOfWeekyear().roundFloorCopy();
the standard week(星期日)的最后一天使用roundCeilingCopy和minusDays ...
LocalDate lastDateOfWeek = new LocalDate().weekOfWeekyear().roundCeilingCopy().minusDays( 1 );
也适用于DateTime。并适用于周末(独家)。
DateTime dateTime = new DateTime();
DateTime startOfWeek = dateTime.weekOfWeekyear().roundFloorCopy();
DateTime endOfWeek = dateTime.weekOfWeekyear().roundCeilingCopy();
转储到控制台...
System.out.println( "dateTime " + dateTime );
System.out.println( "startOfWeek " + startOfWeek );
System.out.println( "endOfWeek " + endOfWeek );
跑步时......
dateTime 2014-01-24T00:00:34.955-08:00
startOfWeek 2014-01-20T00:00:00.000-08:00
endOfWeek 2014-01-27T00:00:00.000-08:00
答案 3 :(得分:5)
您可以使用getDayOfWeek()方法为星期一提供1,为星期二提供2,为星期日提供7,为了返回那么多天并到达星期一:
import org.joda.time.DateTime;
public class JodaTest {
public static void main(String[] args) {
DateTime date = new DateTime();
System.out.println(date);
//2011-01-21T15:06:18.713Z
System.out.println(date.minusDays(date.getDayOfWeek()-1));
//2011-01-17T15:06:18.713Z
}
}
答案 4 :(得分:4)
请参阅"Querying DateTimes" of the Joda-Time user guide部分。
以下是我将遵循的一般算法:
dateTime.minusDays(n)