Skip to content

Instantly share code, notes, and snippets.

@juanpabloprado
Last active April 27, 2019 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanpabloprado/d47cb8e71b528876a9824af1b4e0714b to your computer and use it in GitHub Desktop.
Save juanpabloprado/d47cb8e71b528876a9824af1b4e0714b to your computer and use it in GitHub Desktop.
Period Class on the Java Shell tool
jshell> Period P1 = Period.ofYears(1); // 1 year
P1 ==> P1Y
jshell> Period P2 = Period.ofMonths(12) // 1 year
P2 ==> P12M
jshell> Period P3 = Period.ofWeeks(52) // 1 year
P3 ==> P364D
jshell> Period P4 = Period.ofDays(366) // 1 year (leap)
P4 ==> P366D
jshell> Period P5 = Period.of(1, 12, 366) // 3 years
P5 ==> P1Y12M366D
jshell> LocalDate ld1 = LocalDate.of(2000, Month.JANUARY, 1);
ld1 ==> 2000-01-01
jshell> LocalDate ld2 = ld1.plus(P1).plus(P2).plus(P3).plus(P4).plus(P5);
ld2 ==> 2007-01-02
jshell> "Before: " + ld1 + " After: " + ld2
$81 ==> "Before: 2000-01-01 After: 2007-01-02"
jshell> /* Creates a period of 41 years, 2 months, and 3 days */
jshell> Period period1 = Period.parse("P41Y2M3D");
period1 ==> P41Y2M3D
jshell> /* Creates a period of 4 weeks */
jshell> Period period2 = Period.parse("P4W")
period2 ==> P28D
jshell> period2.getDays() + " days";
$84 ==> "28 days"
jshell> Period period = Period.of(5, 1, 14);
period ==> P5Y1M14D
jshell> int years = period.getYears();
years ==> 5
jshell> int months = period.getMonths();
months ==> 1
jshell> import java.time.temporal.ChronoUnit;
jshell> long days = period.get(ChronoUnit.DAYS);
days ==> 14
jshell> years + " years, " + months + " month, " + days + " days"
$90 ==> "5 years, 1 month, 14 days"
jshell> Period p1 = Period.of(1, 1, 1); // 1 year, 1 month, 1 day
p1 ==> P1Y1M1D
jshell> p1.withYears(5); // Changes years only
$3 ==> P5Y1M1D
jshell> p1; // 5 years, 1 month, 1 day
p1 ==> P1Y1M1D
jshell> Period p2 = Period.of(1, 1, 1); // 1 year, 1 month, 1 day
p2 ==> P1Y1M1D
jshell> p2 = p2.withMonths(5); // Changes months only
p2 ==> P1Y5M1D
jshell> p2; // 1 year, 5 months, 1 day
p2 ==> P1Y5M1D
jshell> Period p3 = Period.of(1, 1, 1); // 1 year, 1 month, 1 day
p3 ==> P1Y1M1D
jshell> p3 = p3.withDays(5); // Changes days only
p3 ==> P1Y1M5D
jshell> p3; // 1 year, 1 month, 5 days
p3 ==> P1Y1M5D
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment