Date and Time

How To Get System time using LocalDateTime java 8

Table of Contents

Program

import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;

public class DateSystemDate {
	public static void main(String[] args) {
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
		LocalDateTime now = LocalDateTime.now();
		System.out.println(dtf.format(now));
	}
}

Output

2021/04/11 23:19:18

Description

public static LocalDateTime now()

Obtains the current date-time from the system clock in the default time-zone.
This will query the system clock in the default time-zone to obtain the current date-time.

Using this method will prevent the ability to use an alternate clock for testing because the clock is hard-coded.

Returns:

the current date-time using the system clock and default time-zone, not null

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