Deep dive into the Date and Time in Java
In java.util.date and java.sql.date these two packages are have if we use date from utils package then we will get Sun Nov 10 14:25:26 IST 2024
if we use java.sql.date we get year-month-date
In java 8 introduced new Date and Time Api:
The new API was introduced in the java.time
package, which provides more flexibility and fixes the flaws of the old Date
API. The new classes are immutable and thread safe.
Key Classes in
java.time
package:LocalDate
: Represents a date without time (year, month, day).LocalTime
: Represents a time without a date (hour, minute, second, etc.).LocalDateTime
: Represents both date and time.ZonedDateTime
: Represents date and time with timezone information.Duration
: Represents the amount of time between twotemporal
objects.Period
: Represents a period of time in terms of years, months, and days.ChronoUnit
: Provides methods for working with the different units of time, like days, hours, minutes, etc.Instant
: Immutable and thread-safe, like most classes in thejava.time
package.Date
: Mutable, meaning its value can change after creation. This can lead to unintended bugs when handlingDate
objects in multithreaded environments.
LocalDate methods:
now()
: Gets the current date from the system clock.of()
: Creates a date from a specific year, month, and day.plusDays()
,minusDays()
: Add or subtract days from a date.getYear()
,getMonth()
,getDayOfMonth()
: Get components of a date.ChronoUnit: A utility to measure or add/subtract various time units between two dates or times. Can represent both date and time units.
Duration: Used for precise, short-term time intervals measured in seconds, minutes, or hours.
Period: Best for representing longer, date-based intervals in years, months, and days.