In the world of programming, handling dates and times is a common task. Whether you're building a calendar application, tracking events, or managing user schedules, understanding how to work with dates in Java is essential. In this tutorial, we'll explore Java's date and time API, focusing on classes like LocalDate, LocalTime, LocalDateTime, and DateTimeFormatter. By the end of this lesson, you'll be able to manipulate and format dates and times effectively.
Java provides a robust set of classes in the java.time package to handle date and time operations. These classes are designed to be immutable, thread-safe, and easy to use. We'll start by looking at how to create and manipulate dates using LocalDate, then move on to times with LocalTime, and finally combine them into a single point in time with LocalDateTime. We'll also learn how to format these date-time objects using DateTimeFormatter.
LocalDate represents a date without time-zone in the ISO-8601 calendar system (yyyy-MM-dd). It's perfect for handling just dates, such as birthdays or event dates.
You can create a LocalDate object using several factory methods:
1import java.time.LocalDate;23public class LocalDateExample {4public static void main(String[] args) {5// Current date6LocalDate today = LocalDate.now();7System.out.println("Today's date: " + today);89// Specific date10LocalDate specificDate = LocalDate.of(2023, 10, 15);11System.out.println("Specific date: " + specificDate);12};13}
Today's date: 2023-10-15 Specific date: 2023-10-15
You can easily manipulate dates by adding or subtracting days, months, or years:
1import java.time.LocalDate;2import java.time.temporal.ChronoUnit;34public class LocalDateManipulation {5public static void main(String[] args) {6LocalDate today = LocalDate.now();78// Adding days9LocalDate tomorrow = today.plusDays(1);10System.out.println("Tomorrow: " + tomorrow);1112// Subtracting months13LocalDate lastMonth = today.minusMonths(1);14System.out.println("Last month: " + lastMonth);1516// Adding years17LocalDate nextYear = today.plusYears(1);18System.out.println("Next year: " + nextYear);1920// Calculating difference in days21long daysBetween = ChronoUnit.DAYS.between(today, tomorrow);22System.out.println("Days between today and tomorrow: " + daysBetween);23}24}
Tomorrow: 2023-10-16 Last month: 2023-09-15 Next year: 2024-10-15 Days between today and tomorrow: 1
LocalTime represents a time without a time-zone in the ISO-8601 calendar system (HH:mm:ss). It's useful for handling just times, such as appointment times or meeting start times.
You can create a LocalTime object using several factory methods:
1import java.time.LocalTime;23public class LocalTimeExample {4public static void main(String[] args) {5// Current time6LocalTime now = LocalTime.now();7System.out.println("Current time: " + now);89// Specific time10LocalTime specificTime = LocalTime.of(14, 30);11System.out.println("Specific time: " + specificTime);12}13}
Current time: 14:30:00.123456789 Specific time: 14:30
You can manipulate times by adding or subtracting hours, minutes, or seconds:
1import java.time.LocalTime;2import java.time.temporal.ChronoUnit;34public class LocalTimeManipulation {5public static void main(String[] args) {6LocalTime now = LocalTime.now();78// Adding hours9LocalTime later = now.plusHours(2);10System.out.println("Later: " + later);1112// Subtracting minutes13LocalTime earlier = now.minusMinutes(30);14System.out.println("Earlier: " + earlier);1516// Adding seconds17LocalTime preciseLater = now.plusSeconds(45);18System.out.println("Precise later: " + preciseLater);1920// Calculating difference in minutes21long minutesBetween = ChronoUnit.MINUTES.between(now, later);22System.out.println("Minutes between now and later: " + minutesBetween);23}24}
Later: 16:30:00.123456789 Earlier: 14:00:00.123456789 Precise later: 14:30:45.123456789 Minutes between now and later: 120
LocalDateTime represents a date-time without time-zone in the ISO-8601 calendar system (yyyy-MM-ddTHH:mm:ss). It combines the functionality of LocalDate and LocalTime.
You can create a LocalDateTime object using several factory methods:
1import java.time.LocalDateTime;23public class LocalDateTimeExample {4public static void main(String[] args) {5// Current date-time6LocalDateTime now = LocalDateTime.now();7System.out.println("Current date-time: " + now);89// Specific date-time10LocalDateTime specificDateTime = LocalDateTime.of(2023, 10, 15, 14, 30);11System.out.println("Specific date-time: " + specificDateTime);12}13}
Current date-time: 2023-10-15T14:30:00.123456789 Specific date-time: 2023-10-15T14:30
You can manipulate date-times by adding or subtracting days, months, years, hours, minutes, or seconds:
1import java.time.LocalDateTime;2import java.time.temporal.ChronoUnit;34public class LocalDateTimeManipulation {5public static void main(String[] args) {6LocalDateTime now = LocalDateTime.now();78// Adding days9LocalDateTime tomorrow = now.plusDays(1);10System.out.println("Tomorrow: " + tomorrow);1112// Subtracting months13LocalDateTime lastMonth = now.minusMonths(1);14System.out.println("Last month: " + lastMonth);1516// Adding years17LocalDateTime nextYear = now.plusYears(1);18System.out.println("Next year: " + nextYear);1920// Adding hours21LocalDateTime later = now.plusHours(2);22System.out.println("Later: " + later);2324// Subtracting minutes25LocalDateTime earlier = now.minusMinutes(30);26System.out.println("Earlier: " + earlier);2728// Calculating difference in days29long daysBetween = ChronoUnit.DAYS.between(now, tomorrow);30System.out.println("Days between today and tomorrow: " + daysBetween);31}32}
Tomorrow: 2023-10-16T14:30:00.123456789 Last month: 2023-09-15T14:30:00.123456789 Next year: 2024-10-15T14:30:00.123456789 Later: 2023-10-15T16:30:00.123456789 Earlier: 2023-10-15T14:00:00.123456789 Days between today and tomorrow: 1
DateTimeFormatter is used to format date-time objects into readable strings and parse strings back into date-time objects.
You can format LocalDate, LocalTime, or LocalDateTime using a formatter:
1import java.time.LocalDate;2import java.time.LocalDateTime;3import java.time.LocalTime;4import java.time.format.DateTimeFormatter;56public class DateTimeFormatterExample {7public static void main(String[] args) {8LocalDate date = LocalDate.now();9LocalTime time = LocalTime.now();10LocalDateTime dateTime = LocalDateTime.now();1112// Custom formatter13DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");14DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");15DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");1617// Formatting18String formattedDate = date.format(dateFormatter);19String formattedTime = time.format(timeFormatter);20String formattedDateTime = dateTime.format(dateTimeFormatter);2122System.out.println("Formatted Date: " + formattedDate);23System.out.println("Formatted Time: " + formattedTime);24System.out.println("Formatted DateTime: " + formattedDateTime);25}26}
Formatted Date: 15-10-2023 Formatted Time: 02:30 PM Formatted DateTime: 2023-10-15 14:30:00
You can parse strings back into date-time objects using a formatter:
1import java.time.LocalDate;2import java.time.LocalDateTime;3import java.time.LocalTime;4import java.time.format.DateTimeFormatter;56public class DateTimeFormatterParsingExample {7public static void main(String[] args) {8// Custom formatter9DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");10DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("hh:mm a");11DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");1213// Parsing14LocalDate date = LocalDate.parse("15-10-2023", dateFormatter);15LocalTime time = LocalTime.parse("02:30 PM", timeFormatter);16LocalDateTime dateTime = LocalDateTime.parse("2023-10-15 14:30:00", dateTimeFormatter);1718System.out.println("Parsed Date: " + date);19System.out.println("Parsed Time: " + time);20System.out.println("Parsed DateTime: " + dateTime);21}22}
Parsed Date: 2023-10-15 Parsed Time: 14:30 Parsed DateTime: 2023-10-15T14:30
Let's create a simple application that asks the user for their birthdate and calculates how old they are in years.
1import java.time.LocalDate;2import java.time.Period;3import java.time.format.DateTimeFormatter;4import java.util.Scanner;56public class AgeCalculator {7public static void main(String[] args) {8Scanner scanner = new Scanner(System.in);910// Input format11DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");1213System.out.print("Enter your birthdate (dd-MM-yyyy): ");14String inputDate = scanner.nextLine();1516try {17// Parse the input date18LocalDate birthDate = LocalDate.parse(inputDate, formatter);1920// Calculate age21Period age = Period.between(birthDate, LocalDate.now());2223System.out.println("You are " + age.getYears() + " years old.");24} catch (Exception e) {25System.out.println("Invalid date format. Please enter the date in dd-MM-yyyy format.");26}2728scanner.close();29}30}
Enter your birthdate (dd-MM-yyyy): 15-10-1990 You are 33 years old.
| Concept | Description |
|---|---|
LocalDate | Represents a date without time-zone in the ISO-8601 calendar system. |
LocalTime | Represents a time without a time-zone in the ISO-8601 calendar system. |
LocalDateTime | Represents a date-time without time-zone in the ISO-8601 calendar system. |
DateTimeFormatter | Used to format and parse date-time objects into readable strings. |
In the next tutorial, we'll explore Java exceptions, including how to handle errors gracefully using try-catch blocks and custom exception classes. Understanding exceptions is crucial for building robust and error-resistant applications.
Stay tuned!