Date Object Creation
Methods of Creating Date Objects
1. Using java.util.Date
// Current date and time
Date currentDate = new Date();
// Date from specific milliseconds
Date specificDate = new Date(1234567890L);
// Date from year, month, day parameters
Date customDate = new Date(2023, 5, 15);
Modern Date Creation Techniques
2. java.time Package Methods
graph TD
A[Date Object Creation] --> B[LocalDate]
A --> C[LocalDateTime]
A --> D[Instant]
LocalDate Creation
// Current date
LocalDate today = LocalDate.now();
// Specific date
LocalDate specificDate = LocalDate.of(2023, 6, 20);
// Parse from string
LocalDate parsedDate = LocalDate.parse("2023-06-20");
Date Creation Comparison
Method |
Class |
Description |
now() |
LocalDate |
Current date |
of() |
LocalDate |
Specific date |
parse() |
LocalDate |
String to date |
LocalDateTime Creation
// Current date and time
LocalDateTime currentDateTime = LocalDateTime.now();
// Specific date and time
LocalDateTime specificDateTime = LocalDateTime.of(2023, 6, 20, 14, 30);
Advanced Date Creation
Instant for Timestamp
// Current timestamp
Instant currentTimestamp = Instant.now();
// Timestamp from milliseconds
Instant specificTimestamp = Instant.ofEpochMilli(1623456789000L);
Best Practices
- Use
java.time
classes for new projects
- Avoid legacy
Date
constructors
- Use appropriate method based on requirements
Code Example: Comprehensive Date Creation
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Instant;
public class DateCreationDemo {
public static void main(String[] args) {
// Various date creation methods
LocalDate today = LocalDate.now();
LocalDate specificDate = LocalDate.of(2023, 6, 20);
LocalDateTime currentTime = LocalDateTime.now();
Instant timestamp = Instant.now();
System.out.println("Today: " + today);
System.out.println("Specific Date: " + specificDate);
System.out.println("Current Time: " + currentTime);
System.out.println("Timestamp: " + timestamp);
}
}
LabEx recommends mastering these date creation techniques for efficient Java programming.