What is Period.ofWeeks() in Java?

Overview

The ofWeeks() is a static methodStatic methods can be accessed without creating a new object. of the Period class. We use it to get an instance of the Period class representing the number of weeks. The period results are based on days, with the number of days equal to the number of weeks multiplied by 7. The value for years and months is zero.

The ofWeeks() method is defined in the Period class, which is defined in the java.time package. To import the Period class, let’s check the following import statement.

Syntax


import java.time.Period;

public static Period ofWeeks(int weeks)

Parameters

int weeks: It is the number of weeks. It can be positive or negative.

Return value

This method returns an instance of the Period class.

Code

import java.time.Period;
public class Main{
public static void main(String[] args) {
int numWeeks = 13;
Period period = Period.ofWeeks(numWeeks);
System.out.println("Positive Weeks - " + period);
numWeeks = -13;
period = Period.ofWeeks(numWeeks);
System.out.println("Negative Weeks - " + period);
}
}

Explanation

  • Lines 6 to 8: We create the Period class object with the positive number of weeks, and display the resulting object to the console.

  • Lines 10 to 12: We create the Period class object with the negative number of weeks, and display the resulting object to the console.

Free Resources