Java 8 Date API – Get cardinal position of the day in the month

  • A+

Inspired by the following posts

I need a function that returns the cardinal position for a given day in the month, for example:

01/01/1970 = 1 because it's the first Thursday in January, 1970

02/01/1970 = 1 because it's the first Friday in January, 1970

19/01/1970 = 3 because it's the third Monday in January, 1970

31/01/1970 = 5 because it's the fifth Saturday in January, 1970

What have I tried? - Nothing...I don't even know where to start; the Java 8 date/time API is pretty new to me.

Ideally I want a function with this signature:

public int getCardinalPosition(TemporalAccessor temporal) {     ... } 


Well, take 19/01/1970. Subtract 7 days from that and it's.. still january. Subtract 7 days again and.. still january. Subtract 7 days a 4th time and.. oh hey it's no longer january. The 4th time you removed 7 days, it ceased to be the right month.

That's all you need here.

Relevant methods: a for loop, a counter, and.. the minusDays(7) method, and getMonth().


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: