Have a look on Java SE 8 Date and Time
Are you still using java.util.Date and SimpleDateFormatter?
If so, read the article in the link below to leverage the power of java.time, the API for Date and Time from Java 8.
―Core Ideas
―LocalDate and LocalTime
―Creating Objects
―Truncation
―Time Zones
―Time Zone Classes
―Periods
―Durations
―Chronologies
―The Rest of the API
Java SE 8 shipped with a new date and time API in java.time that offers greatly improved safety and functionality for developers. The new API models the domain well, with a good selection of classes for modeling a wide variety of developer use cases.
https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html
Time formatting and parsing with DateTimeFormatter
DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.
// DON'T
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); String formattedDate = dateFormat.format(now); Date parsedDate = dateFormat.parse(formattedDate);
// DO
LocalDate now = LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
String formattedDate = now.format(formatter);
LocalDate parsedDate = LocalDate.parse(formattedDate, formatter);Getting time span between two points in time
Duration is an amount of time represented in seconds, minutes and hours. Has nanosecond precision.
Its method between(Temporal startInclusive, Temporal endExclusive) obtains a Duration representing the duration between two temporal objects.
// DON'T
GregorianCalendar calendar = new GregorianCalendar(); Date now = new Date(); calendar.add(Calendar.HOUR, 1); Date hourLater = calendar.getTime(); long elapsed = hourLater.getTime() - now.getTime();
// DO
LocalDateTime now = LocalDateTime.now(); LocalDateTime hourLater = LocalDateTime.now().plusHours(1); Duration span = Duration.between(now, hourLater);
Extracting specific fields
LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second.
It has getters and setters to access date fields.
// DON'T
int day= new GregorianCalendar().get(Calendar.DAY_OF_MONTH); int month = new GregorianCalendar().get(Calendar.MONTH); int year = new GregorianCalendar().get(Calendar.YEAR); int hour= new GregorianCalendar().get(Calendar.HOUR); int minute = new GregorianCalendar().get(Calendar.MINUTE); int second = new GregorianCalendar().get(Calendar.SECOND);
// DO
int day = LocalDateTime.now().getDayOfMonth();//16 Month month = LocalDateTime.now().getMonth();//JANUARY int year = LocalDateTime.now().getYear();//2020 int hour = LocalDateTime.now().getHour();//7 int minute = LocalDateTime.now().getMinute();//32 int second = LocalDateTime.now().getSecond();//11
Time zone conversion
ZonedDateTime is an immutable representation of a date-time with a time-zone.
This class stores all date and time fields, to a precision of nanoseconds, and a time-zone, with a zone offset used to handle ambiguous local date-times.
A ZoneID is a time-zone ID, such as Europe/Paris.
// DON'T
GregorianCalendar calendar = new GregorianCalendar(); calendar.setTimeZone(TimeZone.getTimeZone("CET")); Date centralEastern = calendar.getTime();
// DO
ZonedDateTime centralEastern = LocalDateTime.now().atZone(ZoneId.of("CET"));Adding and subtracting time
// DON'T
GregorianCalendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR_OF_DAY, -5);
Date fiveHoursBefore = calendar.getTime();// DO
LocalDateTime fiveHoursBefore = LocalDateTime.now().minusHours(5);
// SEE ALSO
LocalDateTime plus(long amountToAdd, TemporalUnit unit) LocalDateTime plus(TemporalAmount amountToAdd) LocalDateTime plusDays(long days) LocalDateTime plusHours(long hours) LocalDateTime plusMinutes(long minutes) LocalDateTime plusMonths(long months) LocalDateTime plusNanos(long nanos) LocalDateTime plusSeconds(long seconds) LocalDateTime plusWeeks(long weeks) LocalDateTime plusYears(long years) LocalDateTime minus(long amountToSubtract, TemporalUnit unit) LocalDateTime minus(TemporalAmount amountToSubtract) LocalDateTime minusDays(long days) LocalDateTime minusHours(long hours) LocalDateTime minusMinutes(long minutes) LocalDateTime minusMonths(long months) LocalDateTime minusNanos(long nanos) LocalDateTime minusSeconds(long seconds) LocalDateTime minusWeeks(long weeks) LocalDateTime minusYears(long years)
Truncating
Truncating resets all time fields smaller than the specified field.
In the example below minutes and everything below will be set to zero
// DON'T
Calendar now = Calendar.getInstance(); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); now.set(Calendar.MILLISECOND, 0); Date truncated = now.getTime();
// DO
LocalTime truncated = LocalTime.now().truncatedTo(ChronoUnit.HOURS);
// SEE ALSO LocalDateTime
LocalDateTime truncatedTo(TemporalUnit unit)
Returns a copy of this LocalDateTime with the time truncated.
Representing specific time
Given:
―LocalDate is a date without a time-zone in the ISO-8601 calendar system, such as 2007-12-03.
―Month is an enum representing the 12 months of the year from 1 (January) to 12 (December).
// DON'T
Date birthDay = new GregorianCalendar(1990, Calendar.DECEMBER, 15).getTime();// DO
LocalDate birthDay = LocalDate.of(1990, Month.DECEMBER, 15);
Altering specific fields
withMonth(int month), it returns a copy of this LocalDateTime with the month-of-year altered.
The time does not affect the calculation and will be the same in the result. If the day-of-month is invalid for the year, it will be changed to the last valid day of the month. This instance is immutable and unaffected by this method call.
// DON'T
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(Calendar.MONTH, Calendar.JUNE);
Date inJune = calendar.getTime();// DO
LocalDateTime inJune = LocalDateTime.now().withMonth(Month.JUNE.getValue());
// SEE ALSO
LocalDateTime with(TemporalAdjuster adjuster) LocalDateTime with(TemporalField field, long newValue) LocalDateTime withDayOfMonth(int dayOfMonth) LocalDateTime withDayOfYear(int dayOfYear) LocalDateTime withHour(int hour) LocalDateTime withMinute(int minute) LocalDateTime withMonth(int month) LocalDateTime withNano(int nanoOfSecond) LocalDateTime withSecond(int second) LocalDateTime withYear(int year)