杰瑞科技汇

java calendar week

Of course! Working with weeks in Java can be a bit tricky because the java.util.Calendar class (the pre-Java 8 standard) has some quirks. The modern and recommended approach is to use the java.time package, introduced in Java 8.

java calendar week-图1
(图片来源网络,侵删)

Let's break down both approaches.


The Modern Approach: java.time (Java 8 and later)

This is the best way to handle date-time operations. It's clearer, less error-prone, and immutable.

The key classes for weeks are:

  • java.time.LocalDate: Represents a date without time (e.g., 2025-10-27).
  • java.time.WeekFields: Defines how a week is structured (e.g., which day is the first day of the week, what is the minimum number of days in the first week of the year). This is crucial because different regions have different conventions.
  • java.time.temporal.WeekFields.ISO: A standard definition where weeks start on Monday and the first week of the year is the one with at least 4 days in January. This is the most common standard.

Getting the Current Week Number

This is the most common task. The "week number" usually refers to the ISO week number.

java calendar week-图2
(图片来源网络,侵删)
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class JavaTimeWeekExample {
    public static void main(String[] args) {
        // Get the current date
        LocalDate today = LocalDate.now();
        System.out.println("Today's Date: " + today);
        // Define the week fields using the ISO standard (Monday is first day of week)
        WeekFields weekFields = WeekFields.ISO;
        // Get the current week number of the year
        int weekNumber = today.get(weekFields.weekOfWeekBasedYear());
        System.out.println("Current ISO Week Number: " + weekNumber);
        // You can also get the week-based year
        int weekBasedYear = today.get(weekFields.weekBasedYear());
        System.out.println("Current Week-Based Year: " + weekBasedYear);
    }
}

Output (will vary based on the current date):

Today's Date: 2025-10-27
Current ISO Week Number: 43
Current Week-Based Year: 2025

Getting the First and Last Day of the Current Week

This is very useful for generating reports or displaying a weekly calendar.

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
public class WeekBoundariesExample {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        // Find the most recent Monday (start of the week)
        LocalDate startOfWeek = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        // Find the upcoming Sunday (end of the week)
        LocalDate endOfWeek = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        System.out.println("Today: " + today);
        System.out.println("Start of this week (Monday): " + startOfWeek);
        System.out.println("End of this week (Sunday): " + endOfWeek);
    }
}

Output (if today is Friday, 2025-10-27):

Today: 2025-10-27
Start of this week (Monday): 2025-10-23
End of this week (Sunday): 2025-10-29

Customizing Week Fields (e.g., US Standard)

In the US, the week often starts on Sunday. You can achieve this easily.

java calendar week-图3
(图片来源网络,侵删)
import java.time.LocalDate;
import java.time.temporal.WeekFields;
import java.util.Locale;
public class CustomWeekFieldsExample {
    public static void main(String[] args) {
        LocalDate today = LocalDate.now();
        System.out.println("Today's Date: " + today);
        // Define US-style week fields: Sunday is the first day of the week
        WeekFields usWeekFields = WeekFields.of(Locale.US);
        // Get the week number using the US definition
        int usWeekNumber = today.get(usWeekFields.weekOfWeekBasedYear());
        System.out.println("Current US Week Number: " + usWeekNumber);
        // Compare with the ISO standard
        WeekFields isoWeekFields = WeekFields.ISO;
        int isoWeekNumber = today.get(isoWeekFields.weekOfWeekBasedYear());
        System.out.println("Current ISO Week Number: " + isoWeekNumber);
    }
}

The Legacy Approach: java.util.Calendar (Java 7 and older)

This approach is more verbose and has known bugs, especially around daylight saving time and week calculations. It's generally best to avoid it in new code, but you might encounter it in legacy systems.

The key constant for week number is Calendar.WEEK_OF_YEAR.

Getting the Current Week Number

import java.util.Calendar;
public class LegacyCalendarWeekExample {
    public static void main(String[] args) {
        // Get a Calendar instance, initialized with the current date and time
        Calendar calendar = Calendar.getInstance();
        // Get the week number of the year
        // Note: The first week is the one with at least one day in the new year.
        // This is different from the ISO standard.
        int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
        System.out.println("Current Week Number (Legacy): " + weekNumber);
        // You can also get other fields
        int year = calendar.get(Calendar.YEAR);
        System.out.println("Current Year: " + year);
    }
}

Important Quirks of Calendar

  1. Week Definition: Calendar defines the first week of the year as the one that contains at least one day. This is not the same as the ISO standard (which requires 4 days). This can lead to different week numbers, especially in early January.
  2. First Day of the Week: The first day of the week depends on the Locale of the Calendar instance. For Locale.US, it's Sunday. For Locale.UK or Locale.FRANCE, it's Monday. This can be very confusing.

Getting the First Day of the Week with Calendar

import java.util.Calendar;
public class LegacyWeekStartExample {
    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        // Set the calendar to today
        calendar.setTimeInMillis(System.currentTimeMillis());
        // Find the first day of the week (e.g., Sunday for US locale)
        // This is a bit of a manual process
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        int firstDayOfWeek = calendar.getFirstDayOfWeek(); // Depends on Locale
        // Calculate how many days to go back
        int daysToSubtract = (dayOfWeek - firstDayOfWeek + 7) % 7;
        calendar.add(Calendar.DAY_OF_MONTH, -daysToSubtract);
        System.out.println("First day of this week (Legacy): " + calendar.getTime());
    }
}

Summary and Comparison

Feature java.time (Modern) java.util.Calendar (Legacy)
Ease of Use Excellent. Fluent, readable API. Poor. Verbose, stateful, confusing.
Immutability Immutable. Thread-safe. Mutable. Not thread-safe.
Week Standards Flexible. WeekFields allows for easy customization (ISO, US, etc.). Rigid/Loc-dependent. Behavior changes with Locale, can be surprising.
Week Definition Clear. WeekFields.ISO is the standard (week with 4+ days). Ambiguous. "First week with at least one day" can lead to different results.
Recommendation Always use for new Java 8+ code. Avoid. Use only when maintaining legacy code.

Final Recommendation

Use java.time. It is the modern, correct, and far superior way to handle date and time operations in Java. The only reason to use java.util.Calendar is if you are working on a project that is stuck on a Java version before 8.

分享:
扫描分享到社交APP
上一篇
下一篇