Interfaces for Custom Date and Time Manipulation in Java


Write a Java program to demonstrate the use of an interface for custom date and time manipulation

  • The DateTimeManipulator interface declares a single method formatDateTime that takes a LocalDateTime object and a pattern string, and returns the formatted date and time string.
  • In the main method of the Main class, an instance of the DateTimeManipulator interface is created using a lambda expression. Inside the lambda expression, the DateTimeFormatter class is used to format the LocalDateTime object according to the provided pattern.
  • The current date and time is obtained using LocalDateTime.now().
  • The pattern for formatting is defined.
  • The formatDateTime method of the DateTimeManipulator interface is called with the current date and time and the pattern.
  • The formatted date and time is printed to the console.

Source Code

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
 
interface DateTimeManipulator
{
	String formatDateTime(LocalDateTime dateTime, String pattern);
}
 
public class Main
{
	public static void main(String[] args)
	{
		DateTimeManipulator dateTimeManipulator = (dateTime, pattern) -> {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
			return dateTime.format(formatter);
		};
 
		LocalDateTime now = LocalDateTime.now();
		String formattedDateTime = dateTimeManipulator.formatDateTime(now, "dd-MM-yyyy HH:mm:ss");
 
		System.out.println("Formatted Date and Time : " + formattedDateTime);
	}
}

Output

Formatted Date and Time : 29-11-2023 04:25:17

Example Programs