Show Menu
Cheatography

Java 8 Dates and Times (OCA) Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Java Date Time in Java 8

java 1.0
java.u­til.Da­te;­jav­a.t­ext.Format
java 1.2
java.u­til.Ca­lendar
java 8
java.t­ime.*
java 8 classes: LocalDate, LocalTime, LocalD­ate­Time, Month (1-12), Period, Duration

Creating Dates and Times

static of()
Overriden by LocalData, LocalTime and LocalD­ateTime
LocalD­ate.of­(y,­m.d);
m: int or Month(­1-12)
LocalT­ime.of­(h,­mi,­s,ns)
ns: nano second
LocalD­ate­Tim­e.o­f(y­,m,­d,h­,mi­,s,ns)
LocalD­ate­Tim­e.o­f(d,t)
static now()
Overriden by LocalData, LocalTime and LocalD­ateTime
static parse(s,f)
Overriden by LocalData, LocalTime and LocalD­ateTime
LocalD­ate­Tim­e.p­ars­e(s,f)
f must be DateTi­meF­orm­atter
LocalDate d= new LocalD­ate() //not compiled
LocalDate d= LocalD­ate.of­(20­15,­2,30); //not compile

Manipu­lating Dates and Times

plusXx­x(int)
minusX­xx(int)
return new immutable, original not changed, like String
chain of method on date and time
getXxx(); //Xxx= DayOfW­eek­,Da­yOf­Year, Month, Year
dt1.is­Bef­ore­(dt2)
dt1.is­Aft­er(dt2)
Xxx= Years / Months /Days/­Hou­rs/­Min­ute­s/S­eco­nds­/Nanos;
Java 8 date & time are immutable, like String objects.
 

Peroid and Duration

java.t­ime.Pe­riod; Java.t­ime.Du­ration;
4 ways to create a period
Period.of­Xxx­(int); //Xxx=­Yea­rs,­Mon­ths­,Days
Period.of(int years,int months, int days);
Period.be­tween (d1,d2)
Period.pa­rse­("P1­Y2M­3W4­D");­//same as Period.of(1, 2, 25)
Modify period
plusXx­x(int); //Days­|We­eks­|Mo­nth­s|Years
minusX­xx(int)
Use period
dt.plu­s/m­inn­us(­per­iod);
d.plus­/mi­nus­(pe­riod);
time.p­lus­/mi­nus­(du­rat­ion); //if input period, Unsupp­ort­edT­emp­ora­lTy­peE­xce­ption
Chain of Periods method does not make sense and raise compiler error

Formatting

2 methods to create a formatter
DateTi­meF­orm­atter f=Date­Tim­eFo­rma­tte­r.ofXxx
(Forma­tSt­yle.SH­ORT­|ME­DIU­M|L­ONG­|FULL);
DateTi­meF­orm­atter f=Date­Tim­eFo­rma­tte­r.o­fPa­ttern
("yy­yy-­MMMM-dd hh:mm:­ss"); //M 1 MM 01 MMM Jan MMMM January
Standard formatter:
DateTi­meF­orm­att­er.I­SO­_LO­CAL­_DA­TE/­TIM­E/D­ATETIME
ISO_LO­CAL­_DA­TETIME: '2011-­12-­03T­10:­15:30'
3 ways to use formatter
f.format( date/t­ime­/da­tet­ime_obj );
date/t­ime­/da­tet­ime­_ob­j.f­ormat( f );
LocalD­­at­e­/­Ti­­me/­­Da­t­e­Ti­­me.p­­a­r­s­e(­­String s, DateTi­­me­F­o­rm­­atter f);
1 Xxx = Locali­zed­Date, Locali­zed­Tim­e,L­oca­liz­edD­ateTime
2 date and time format legal for datatime object, datatime format not legal for date or time object