Date and Time

Date toInstant() Method in Java Code with Examples

Table of Contents

Program

import java.util.Date;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
public class FormatInstant
{
public static void main(String[] args)
{
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern(“yyyy-MM-dd HH:mm:ss”).withZone(ZoneId.systemDefault());
System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));
}
}

Output

2021-04-12 11:29:47

Description

public static DateTimeFormatter ofPattern​(String pattern)

Creates a formatter using the specified pattern.
This method will create a formatter based on a simple pattern of letters and symbols as described in the class documentation. For example, d MMM uuuu will format 2011-12-03 as ‘3 Dec 2011’.
The formatter will use the default FORMAT locale. This can be changed using withLocale(Locale) on the returned formatter. Alternatively use the ofPattern(String, Locale) variant of this method.
The returned formatter has no override chronology or zone. It uses SMART resolver style.

Parameters:

pattern – the pattern to use, not null

Returns:

the formatter based on the pattern, not null

Throws:

IllegalArgumentException – if the pattern is invalid

public String format​(TemporalAccessor temporal)

Formats a date-time object using this formatter.
This formats the date-time to a String using the rules of the formatter.

Parameters:

temporal – the temporal object to format, not null

Returns:

the formatted string, not null

Throws:

DateTimeException – if an error occurs during formatting