Home »
Java »
Java Reference »
Java LocalDateTime Class
Java LocalDateTime Class | ofEpochSecond() Method with Example
LocalDateTime Class ofEpochSecond() method: Here, we are going to learn about the ofEpochSecond() method of LocalDateTime Class with its syntax and example.
Submitted by Preeti Jain, on June 08, 2020
LocalDateTime Class ofEpochSecond() method
- ofEpochSecond() method is available in java.time package.
- ofEpochSecond() method is used to represent an instance of this LocalDateTime by using the given seconds, nanos, and ZoneOffset from the java epoch standard format of 1970-01-01T00:00:00Z.
- ofEpochSecond() method may throw an exception at the time of representing seconds in epoch format.
DateTimeException – This exception may throw when this LocalDateTime value reaches out of the min or max instant.
- ofEpochSecond() method is a static method and it is accessible with the class name and if we try to access these methods with the class object then we will not get an error.
Syntax:
public static LocalDateTime ofEpochSecond(
long sec_val,
int nanos_val,
ZoneOffset off
);
Parameter(s):
- long sec_val – represents the number of seconds in value since 1970-01-01T00:00:00Z.
- int nanos_val – represents the nanoseconds in a second when the number of nanoseconds starts from 0 to 999,999,999.
- ZoneOffset off – represents the zone offset.
Return value:
The return type of this method is LocalDateTime, it returns the LocalDateTime that holds the value created by using the given parameters from the epoch of 1970-01-01T00:00:00Z.
Example:
// Java program to demonstrate the example
// of ofEpochSecond() method of LocalDateTime
import java.time.*;
public class OfEpochSecondOfLocalDateTime {
public static void main(String args[]) {
long sec = 150;
int nanos = 20000;
// Instantiates a ZoneOffset
ZoneOffset zo_off = ZoneOffset.ofHoursMinutes(10, 30);
// Here, this method creates a date-time
// object by using a sec, nanos and
// ZoneOffset from epoch of
// 1970-01-01T00:00:00Z
LocalDateTime da_ti = LocalDateTime.ofEpochSecond(sec, nanos, zo_off);
// Display da_ti
System.out.print("LocalDateTime.ofEpochSecond(sec,nanos,zo_off): ");
System.out.println(da_ti);
}
}
Output
LocalDateTime.ofEpochSecond(sec,nanos,zo_off): 1970-01-01T10:32:30.000020