Java Time and Date Example
1. Introduction
In this article, we will take a look at Time and Date Classes using Java 8. Java Util classes Date and Calendar had features missing for handling Date and Time. In Java 8, Date and Time classes were introduced to handle the missing features.
2. Java Time and Date Example
Java Time package has the following classes: LocalDate, LocalTime, LocalDateTime, MonthDay, OffsetTime, OffsetDateTime, Clock, ZonedDateTime, ZoneId, ZoneOffset, Year, Instant, DayOfWeek, Month,YearMonth, Period, and Duration.
2.1 Prerequisites
Java 8 is required on the Linux, Windows or Mac operating system. Eclipse Oxygen can be used for this example.
2.2 Download
You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.
2.3 Setup
2.3.1 Java Setup
Below are the setup commands required for the Java Environment.
Setup
JAVA_HOME="/desktop/jdk1.8.0_73" export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
2.4 IDE
2.4.1 Eclipse Oxygen Setup
The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.
2.4.2 Launching IDE
Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. The eclipse screen pops up as shown in the screenshot below:
You can select the workspace from the screen which pops up. The attached image shows how it can be selected.
You can see the eclipse workbench on the screen. The attached screenshot shows the Eclipse project screen.
Java Hello World
class prints the greetings. The screenshot below is added to show the class and execution on the eclipse.
2.5 Date, Time Classes Overview
Initially Java had the following Date and Time classes : java.util.Date
, java.sql.Date
, java.util.Calendar
, java.util.GregorianCalendar
, java.util.TimeZone
, java.sql.Time
, and java.sql.Timestamp
. Java LocalDate
class is used for handling Dates in yyyy-MM-dd format. LocalDate
implements the interface ChronoLocalDate
. Java LocalTime
class is used for handling time in hour-minute-second format. LocalTime
implements the Comparable
interface.
2.6 Constructors
Date class
has two constructors which are default constructor and one with time as the parameter. The default constructor creates the date with the current day and time as now. The constructor of Date class
with parameter as time takes time in milliseconds to create Date class
.
Date Constructors
Date date = new Date(); Date tDate = new Date(10000);
Java.sql.Time
has a constructor which takes a time parameter.
Time Constructors
Time time = new Time(100);
2.7 Methods
LocalDate
has methods now
, of
, parse
, plusDays
, minus
, getDayOfWeek
,getDayOfMonth
,isLeapYear
, isBefore
, isAfter
, and atStartOfDay
.
LocalDate Methods
LocalDate localDate = LocalDate.now(); LocalDate.of(2020, 03, 10); LocalDate.parse("2020-04-10"); LocalDate dayAfterTomorrow = LocalDate.now().plusDays(2); LocalDate previousTowMonthSameDay = LocalDate.now().minus(2, ChronoUnit.MONTHS); int eleven = LocalDate.parse("2020-07-11").getDayOfMonth(); boolean isNotBefore = LocalDate.parse("2019-07-21") .isBefore(LocalDate.parse("2020-03-01")); boolean isNotAfter = LocalDate.parse("2020-03-12") .isAfter(LocalDate.parse("2020-04-11")); LocalDateTime startDay = LocalDate.parse("2020-04-12").atStartOfDay(); LocalDate monthFirstDay = LocalDate.parse("2020-04-12") .with(TemporalAdjusters.firstDayOfMonth());
LocalTime
has methods now
, of
, parse
, plus
,getHour
, isBefore
, and isAfter
.
LocalTime Methods
LocalTime nowTime = LocalTime.now(); LocalTime sevenThirty = LocalTime.parse("07:30"); LocalTime sevenThirty = LocalTime.of(7, 30); LocalTime eightThirty = LocalTime.parse("07:30").plus(1, ChronoUnit.HOURS); int eight = LocalTime.parse("08:30").getHour(); boolean isNotBefore = LocalTime.parse("08:30").isBefore(LocalTime.parse("07:30")); LocalTime maximumTime = LocalTime.MAX
LocalDateTime
has methods now
, of
, parse
, plusDays
, minusHours
, and getMonth
.
LocalTime Methods
LocalDateTime.now(); LocalDateTime.of(2020, Month.MARCH, 10, 06, 30); LocalDateTime.parse("2020-02-20T06:30:00"); LocalDateTime.now().plusDays(2); LocalDateTime.now().minusHours(3); LocalDateTime.now().getMonth();
2.8 LocalDate Examples
LocalDate
Class example is shown in the code below:
import java.time.LocalDate; public class LocalDateOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LocalDate localDate = LocalDate.now(); LocalDate yesterdayDate = localDate.minusDays(1); LocalDate dayAfterTomorrowDate = yesterdayDate.plusDays(3); System.out.println("Date Today "+ localDate); System.out.println("Date Yesterday "+yesterdayDate); System.out.println("Date DayAfterTommorow "+dayAfterTomorrowDate); } }
The code above will output:
LocalDate Example
Date Today 2020-04-22 Date Yesterday 2020-04-21 Date DayAfterTommorow 2020-04-24
2.9 LocalTime Examples
LocalTime
example is shown in the code below:
import java.time.LocalTime; public class LocalTimeOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LocalTime localTime = LocalTime.now(); System.out.println("Time Now "+ localTime); } }
The code above will output:
LocalTime Examples
Time Now 16:36:59.374335
2.10 LocalDateTime Examples
LocalDateTime
example is shown in the code below:
import java.time.LocalDateTime; public class LocalDateTimeOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LocalDateTime localDateTime = LocalDateTime.of(2020, 4, 15, 5, 30, 40, 50000); System.out.println("Hour " + localDateTime.getHour()); System.out.println("Minute " + localDateTime.getMinute()); System.out.println("Second " + localDateTime.getSecond()); System.out.println("Nano " + localDateTime.getNano()); System.out.println("Year " + localDateTime.getYear()); System.out.println("Month " + localDateTime.getMonth()); System.out.println("Day of Month " + localDateTime.getDayOfMonth()); } }
The code above will output:
LocalDateTime Examples
Hour 5 Minute 30 Second 40 Nano 50000 Year 2020 Month APRIL Day of Month 15
2.11 ZonedDateTime Examples
ZonedDateTime
example is shown in the code below:
import java.time.ZonedDateTime; public class ZonedDateTimeOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub ZonedDateTime zonedDateTime = ZonedDateTime.parse("2020-04-15T08:20:10+05:30[Asia/Kolkata]"); System.out.println("ZonedDateTime "+zonedDateTime); } }
The code above will output:
ZonedDateTime Examples
ZonedDateTime 2020-04-15T08:20:10+05:30[Asia/Kolkata]
2.12 Period and Duration class Examples
Period
class example is shown in the code below:
import java.time.LocalDate; import java.time.Period; import java.time.temporal.Temporal; public class PeriodOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Period period = Period.ofDays(24); Temporal temporal = period.addTo(LocalDate.now()); System.out.println("Temporal "+temporal); } }
The code above will output:
Period Examples
Temporal 2020-05-16
Duration
class example is shown in the code below:
import java.time.Duration; import java.time.LocalTime; import java.time.temporal.ChronoUnit; public class DurationOperations { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Duration duration = Duration.between(LocalTime.NOON,LocalTime.MAX); System.out.println("Duration "+duration.get(ChronoUnit.SECONDS)); } }
The code above will output:
Duration Examples
Duration 43199
2.13 Conversion : LocalDateTime & Date/Calendar
LocalDateTime
Conversion to Date
class is shown in the code below:
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.util.Calendar; import java.util.Date; public class LocalDateTimeConversion { public static Date convertLocalTimeToDate(LocalTime localTime) { Calendar calendar = Calendar.getInstance(); calendar.clear(); //assuming year/month/date information is not important calendar.set(0, 0, 0, localTime.getHour(), localTime.getMinute(), localTime.getSecond()); return calendar.getTime(); } public static Date convertLocalDateToDate(LocalDate localDate) { Calendar calendar = Calendar.getInstance(); calendar.clear(); //assuming start of day calendar.set(localDate.getYear(), localDate.getMonthValue()-1, localDate.getDayOfMonth()); return calendar.getTime(); } public static Date convertLocalDateTimeToDate(LocalDateTime localDateTime) { Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(localDateTime.getYear(), localDateTime.getMonthValue()-1, localDateTime.getDayOfMonth(), localDateTime.getHour(), localDateTime.getMinute(), localDateTime.getSecond()); return calendar.getTime(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Date convertedDate = convertLocalTimeToDate(LocalTime.now()); System.out.println("Local Time to Date "+convertedDate); convertedDate = convertLocalDateToDate(LocalDate.now()); System.out.println("Local Date to Date "+convertedDate); convertedDate = convertLocalDateTimeToDate(LocalDateTime.now()); System.out.println("LocalDate Time to Date "+convertedDate); } }
The code above will output:
LocalDateTime Conversion Examples
Local Time to Date Wed Dec 31 16:49:23 UTC 2 Local Date to Date Wed Apr 22 00:00:00 UTC 2020 LocalDate Time to Date Wed Apr 22 16:49:23 UTC 2020
Calendar
Conversion to Time
is shown in the code below:
import java.util.Calendar; public class CalendarTimeConversion { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Calendar calendarInstance = Calendar.getInstance(); System.out.println("Today's Date is : " + calendarInstance.getTime()); calendarInstance.add(Calendar.DATE, -5); System.out.println("5 days back Date " + calendarInstance.getTime()); calendarInstance.add(Calendar.MONTH, 3); System.out.println("3 months after Date " + calendarInstance.getTime()); calendarInstance.add(Calendar.YEAR, 1); System.out.println("1 year after Date " + calendarInstance.getTime()); } }
The code above will output:
Calendar-Time Conversion Examples
Today's Date is : Wed Apr 22 16:51:48 UTC 2020 5 days back Date Fri Apr 17 16:51:48 UTC 2020 3 months after Date Fri Jul 17 16:51:48 UTC 2020 1 year after Date Sat Jul 17 16:51:48 UTC 2021
2.14 LocalDateTime Formatting Examples
LocalDateTime
Formatting is shown in the code below:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class LocalDateTimeFormatter { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Current Date Time " + currentDateTime); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String formatCurrentDateTime = currentDateTime.format(dateTimeFormatter); System.out.println("After Date Time " + formatCurrentDateTime); } }
The code above will output:
LocalDateTime FormattingExamples
Current Date Time 2020-04-22T16:54:50.202195 After Date Time 2020-04-22 16:54:50
3. Download the Source Code
You can download the full source code of this example here: Java Time and Date Example
This sentence from the article is totally wrong: “Java LocalDate class is used for handling Dates in yyyy-MM-dd format.” A date and a date format are two separate things. The sole purpose of a date format is to define how to display a date in human-readable form and has nothing to do with the data-type. How many people, who may be unfamiliar with java’s date-time API, will read this article and believe that LocalDate class can only handle a specific date format. I can think of a few bad repercussions as a result of this incorrect information.