The Java Date and Time API is used for working with dates, times, and durations in Java. Starting with Java 8, the new java.time
package was introduced to simplify date and time operations.
import java.time.LocalDateTime; public class DateTimeExample { public static void main(String[] args) { // Get current date and time LocalDateTime now = LocalDateTime.now(); System.out.println("Current Date and Time: " + now); } }
The LocalDateTime.now()
method returns the current date and time.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeExample { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); // Format date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formattedDate = now.format(formatter); System.out.println("Formatted Date and Time: " + formattedDate); } }
The DateTimeFormatter
class is used to format the date and time according to a specified pattern.
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DateTimeExample { public static void main(String[] args) { String dateStr = "2024-11-15 15:30:00"; // Parse string into date and time DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); LocalDateTime parsedDate = LocalDateTime.parse(dateStr, formatter); System.out.println("Parsed Date and Time: " + parsedDate); } }
The parse()
method is used to convert a string into a LocalDateTime
object, based on the specified format.