Time Manipulation Methods
Overview of Time Manipulation
Time manipulation in Java involves various operations to modify, compare, and transform time-related objects.
Key Manipulation Categories
graph TD
A[Time Manipulation] --> B[Creation]
A --> C[Modification]
A --> D[Comparison]
A --> E[Formatting]
Common Time Manipulation Methods
Method Category |
Key Operations |
Example Methods |
Creation |
Instantiate time objects |
now() , of() , parse() |
Modification |
Change time values |
plusDays() , minusHours() |
Comparison |
Check time relationships |
isBefore() , isAfter() |
Conversion |
Transform between formats |
atZone() , toLocalDate() |
Time Creation Methods
import java.time.LocalDateTime;
import java.time.LocalDate;
public class TimeCreation {
public static void main(String[] args) {
// Current time
LocalDateTime currentTime = LocalDateTime.now();
// Specific date and time
LocalDate specificDate = LocalDate.of(2023, 6, 15);
// Parsing from string
LocalDate parsedDate = LocalDate.parse("2023-06-15");
}
}
Time Modification Examples
import java.time.LocalDateTime;
public class TimeModification {
public static void main(String[] args) {
LocalDateTime current = LocalDateTime.now();
// Add days
LocalDateTime futureDate = current.plusDays(7);
// Subtract hours
LocalDateTime pastTime = current.minusHours(3);
// Complex modifications
LocalDateTime modifiedTime = current
.plusWeeks(2)
.minusHours(5)
.plusMinutes(30);
}
}
Time Comparison Methods
import java.time.LocalDate;
public class TimeComparison {
public static void main(String[] args) {
LocalDate date1 = LocalDate.of(2023, 6, 15);
LocalDate date2 = LocalDate.of(2023, 7, 20);
// Comparison methods
boolean isBefore = date1.isBefore(date2);
boolean isAfter = date1.isAfter(date2);
boolean isEqual = date1.isEqual(date2);
}
}
Advanced Manipulation Techniques
- Period calculations
- Timezone conversions
- Date range validations
- Complex time arithmetic
At LabEx, we recommend practicing these methods to master Java time manipulation techniques.