Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check a day is in the current week in Java?

Tags:

java

date

Is there easiest way to find any day is in the current week? (this function returns true or false, related to given day is in current week or not).

like image 241
Ikrom Avatar asked Apr 25 '12 10:04

Ikrom


2 Answers

You definitely want to use the Calendar class: http://docs.oracle.com/javase/6/docs/api/java/util/Calendar.html

Here's one way to do it:

public static boolean isDateInCurrentWeek(Date date) {
  Calendar currentCalendar = Calendar.getInstance();
  int week = currentCalendar.get(Calendar.WEEK_OF_YEAR);
  int year = currentCalendar.get(Calendar.YEAR);
  Calendar targetCalendar = Calendar.getInstance();
  targetCalendar.setTime(date);
  int targetWeek = targetCalendar.get(Calendar.WEEK_OF_YEAR);
  int targetYear = targetCalendar.get(Calendar.YEAR);
  return week == targetWeek && year == targetYear;
}
like image 88
Benjamin Cox Avatar answered Oct 18 '22 19:10

Benjamin Cox


Use the Calendar class to get the YEAR and WEEK_OF_YEAR fields and see if both are the same.

Note that the result will be different depending on the locale, since different cultures have different opinions about which day is the first day of the week.

like image 27
Michael Borgwardt Avatar answered Oct 18 '22 21:10

Michael Borgwardt