Java MCQ: Which of the following best describes the purpose of the DateTimeFormatter class in Java 8?
Answer:
Explanation:
The DateTimeFormatter
class in Java 8 is used to convert a date-time object to a String
and vice versa. It is part of the java.time.format
package and provides a flexible and comprehensive way to format and parse date-time objects.
Here’s an example of using DateTimeFormatter
:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeFormatterExample {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formattedDate = now.format(formatter);
System.out.println("Formatted DateTime: " + formattedDate);
}
}
In this example, DateTimeFormatter
is used to format the current date and time (LocalDateTime.now()
) into a string with the pattern "yyyy-MM-dd HH:mm:ss"
. The format()
method is called on the LocalDateTime
object, and the formatted string is printed.
DateTimeFormatter
also supports parsing strings into date-time objects, allowing for easy conversion between string representations and LocalDate
, LocalTime
, LocalDateTime
, and other date-time types in the java.time
package.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html