How to implement java.time.LocalDate using JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

JShell is a REPL (Read-Eval-Print-Loop) interactive tool introduced in Java 9 that takes input, evaluates it, and returns output to a user.

java.util.LocalDate class provides a number of methods to retrieve Date information: Day/Month/Year and related attributes Date meta-information: Classification-related information such as whether a leap year, etc. LocalDate class is immutable, and we can use different methods provided to add and subtract days, months, and years. Each of these returns a new instance of LocalDate.

In the below two code snippets, we can able to print different operations using LocalDate class.

Snippet-1

jshell> import java.time.*;

jshell> LocalDate today = LocalDate.now()
today ==> 2020-04-22

jshell> today.getYear()
$3 ==> 2020

jshell> today.getDayOfWeek()
$4 ==> WEDNESDAY

jshell> today.getDayOfMonth()
$5 ==> 22

jshell> today.getDayOfYear()
$6 ==> 113

jshell> today.getMonth()
$7 ==> APRIL

jshell> today.getMonthValue()
$8 ==> 4

jshell> today.isLeapYear()
$9 ==> true

jshell> today.lengthOfYear()
$10 ==> 366

jshell> today.lengthOfMonth()
$11 ==> 30

Snippet-2

jshell> today.plusDays(50)
$12 ==> 2020-06-11

jshell> today.plusMonths(50)
$13 ==> 2024-06-22

jshell> today.plusYears(50)
$14 ==> 2070-04-22

jshell> today.minusYears(50)
$15 ==> 1970-04-22

jshell> LocalDate yesterYear = today.minusYears(50)
yesterYear ==> 1970-04-22

jshell> today
today ==> 2020-04-22
raja
Published on 22-Apr-2020 17:32:06
Advertisements