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

2020-06-19 07:20发布

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).

标签: java date
5条回答
【Aperson】
2楼-- · 2020-06-19 07:24

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;
}
查看更多
女痞
3楼-- · 2020-06-19 07:26

Simple Kotlin solution:

fun isDateInCurrentWeek(date: DateTime): Boolean {
         val cal = Calendar.getInstance()
         cal.add(Calendar.DAY_OF_WEEK, 0)
         var dt= DateTime(cal.timeInMillis)
         return date in dt..dt.plusDays(6)
        }
查看更多
做自己的国王
4楼-- · 2020-06-19 07:36

This answer is for Android. Put your selected date Calendar object in below method to check your selected date is current week date or not.

private boolean isCurrentWeekDateSelect(Calendar yourSelectedDate) {
    Date ddd = yourSelectedDate.getTime();
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(Calendar.MONDAY);

    c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date monday = c.getTime();
    Date nextMonday= new Date(monday.getTime()+7*24*60*60*1000);

    return ddd.after(monday) && ddd.before(nextMonday);
}

Android already provides the java.util.Calendar class for any date and time related query.

查看更多
老娘就宠你
5楼-- · 2020-06-19 07:40

tl;dr

What's a week? Sunday-Saturday? Monday-Sunday? An ISO 8601 week?

For a standard ISO 8601 week…

YearWeek.now( ZoneId.of( "America/Montreal" ) )
        .equals( 
            YearWeek.from( 
                LocalDate.of( 2017 , Month.JANUARY , 23 ) 
            ) 
        )

java.time

The modern approach uses the java.time classes that supplant the troublesome old date-time classes such as Date & Calendar.

In addition, the ThreeTen-Extra project provides a handy YearWeek class for our purposes here, assuming a standard ISO 8601 week is what you had in mind by the word "week". The documentation for that class summarized the definition of a standard week:

ISO-8601 defines the week as always starting with Monday. The first week is the week which contains the first Thursday of the calendar year. As such, the week-based-year used in this class does not align with the calendar year.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" );
YearWeek ywNow = YearWeek.now( z ) ;  // Get the current week for this specific time zone.

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 ) ;  // Some date.

To see if a particular date is contained within the target YearWeek object’s dates, get the YearWeek of that date and compare by calling equals.

YearWeek ywThen = YearWeek.from( ld ) ;  // Determine year-week of some date.
Boolean isSameWeek = ywThen.equals( ywNow ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Leaving this section intact for history.

Checking for ISO week is easy in Joda-Time 2.3.

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;

DateTimeZone parisTimeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime now = new DateTime( parisTimeZone );
DateTime yesterday = now.minusDays( 1 );
DateTime inThree = now.plusDays( 3 );
DateTime inFourteen = now.plusDays( 14 );

System.out.println( "Now: " + now + " is ISO week: " + now.weekOfWeekyear().get() );
System.out.println( "Same ISO week as yesterday ( " + yesterday + " week "+ yesterday.weekOfWeekyear().get() +" ): " + ( now.weekOfWeekyear().get() == yesterday.weekOfWeekyear().get() ) );
System.out.println( "Same ISO week as inThree ( " + inThree + " week "+ inThree.weekOfWeekyear().get() +" ): " + ( now.weekOfWeekyear().get() == inThree.weekOfWeekyear().get() ) );
System.out.println( "Same ISO week as inFourteen ( " + inFourteen + " week "+ inFourteen.weekOfWeekyear().get() +" ): " + ( now.weekOfWeekyear().get() == inFourteen.weekOfWeekyear().get() ) );

When run…

Now: 2013-12-12T06:32:49.020+01:00 is ISO week: 50
Same ISO week as yesterday ( 2013-12-11T06:32:49.020+01:00 week 50 ): true
Same ISO week as inThree ( 2013-12-15T06:32:49.020+01:00 week 50 ): true
Same ISO week as inFourteen ( 2013-12-26T06:32:49.020+01:00 week 52 ): false
查看更多
forever°为你锁心
6楼-- · 2020-06-19 07:51

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.

查看更多
登录 后发表回答