HomeLanguagesJavaMonth from() method in Java

Month from() method in Java

The from() is a built-in method of the Month ENUM which is used to create a Month instance from a temporal object passed to it as a parameter.

Syntax:

static Month from( TemporalAccessor temporal )

Parameters: This method accepts a single parameter which is a temporal object and cannot be NULL.

Return Value: This method returns a Month instance obtained from a temporal object passed to it as a parameter.

Exception: It throws a DateTimeException if it is not possible to convert the temporal object to a valid month instance.

Below programs illustrate the above method:

Program 1:




import java.time.*;
import java.time.Month;
import java.time.temporal.Temporal;
  
class monthEnum {
    public static void main(String[] args)
    {
        // Convert this Temporal object to month
        Month month = Month.from(ZonedDateTime.now());
  
        System.out.println(month);
    }
}


Output:

MARCH

Program 2:




import java.time.*;
import java.time.Month;
import java.time.temporal.Temporal;
  
class monthEnum {
    public static void main(String[] args)
    {
        ZoneId zoneId = ZoneId.of("UTC+1");
  
        ZonedDateTime zonedDateTime = ZonedDateTime.of(2015, 11, 30, 23, 45, 59, 1234, zoneId);
  
        // Convert this Temporal object to month
        Month month = Month.from(zonedDateTime);
  
        System.out.println(month);
    }
}


Output:

NOVEMBER

Reference: https://docs.oracle.com/javase/8/docs/api/java/time/Month.html#from-java.time.temporal.TemporalAccessor-

RELATED ARTICLES

3 COMMENTS

Most Popular

Dominic
32533 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6913 POSTS0 COMMENTS
Nicole Veronica
12029 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12132 POSTS0 COMMENTS
Shaida Kate Naidoo
7043 POSTS0 COMMENTS
Ted Musemwa
7280 POSTS0 COMMENTS
Thapelo Manthata
6999 POSTS0 COMMENTS
Umr Jansen
6986 POSTS0 COMMENTS