Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

how to identify the week from current date in java

I want to identity the whole week date(From Sunday To Saturday) using current date in java.

For Example: Today is Tuesday - it means I need dates for Tuesday, Monday and Sunday.

If current day is Wednesday - then I need dates from Sunday to Wednesday.

How to achieve this logic in java?

I'm able to get the start of week from current date, but I don't know how to get the remaining day date from Week start date. Is there any java utility available for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For reference, the current date used to formulate the output was Wednesday, 22nd July, 2015 (22/07/2015)

Java 8

LocalDate ld = LocalDate.now();
LocalDate sunday = ld.minusDays(ld.getDayOfWeek().getValue());
LocalDate tommorrow = ld.plusDays(1);
LocalDate date = sunday;
while (date.isBefore(tommorrow)) {
    System.out.println(date);
    date = date.plusDays(1);
}

Prints

2015-07-19
2015-07-20
2015-07-21
2015-07-22

As an alternative

(Which will basically work for all the other mentioned APIs) you could simply walk backwards from today...

LocalDate date = LocalDate.now();
do {
    System.out.println(date);
    date = date.minusDays(1);
} while (date.getDayOfWeek() != DayOfWeek.SATURDAY);

Prints

2015-07-22
2015-07-21
2015-07-20
2015-07-19

JodaTime

LocalDate now = LocalDate.now();
LocalDate sunday = now.minusDays(5).withDayOfWeek(DateTimeConstants.SUNDAY);
LocalDate tommorrow = now.plusDays(1);
LocalDate date = sunday;
while (date.isBefore(tommorrow)) {
    System.out.println(date);
    date = date.plusDays(1);
}

Prints

2015-07-19
2015-07-20
2015-07-21
2015-07-22

Calendar

As a last resort. Remember though, Calendar carries time information, so using before, after and equals may not always do what you think they should...

Calendar cal = Calendar.getInstance();
cal.setFirstDayOfWeek(Calendar.SUNDAY);
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);

Calendar today = Calendar.getInstance();

while (cal.before(today)) {
    System.out.println(cal.getTime());
    cal.add(Calendar.DATE, 1);
}

Prints

Sun Jul 19 15:01:49 EST 2015
Mon Jul 20 15:01:49 EST 2015
Tue Jul 21 15:01:49 EST 2015
Wed Jul 22 15:01:49 EST 2015

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...