Get Last Friday of Month in Java

后端 未结 16 1977
一生所求
一生所求 2020-11-28 11:28

I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Ja

16条回答
  •  情话喂你
    2020-11-28 11:50

    You need to know two things - the number of days in the month, and the weekday the first of the month falls on.

    If the first day of the month is a

    • Sunday, then the last Friday is always the 27th.
    • Monday, then the last Friday is always the 26th.
    • Tuesday, then the last Friday is always the 25th.
    • Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it's the 31st
    • Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it's the 30th.
    • Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it's the 29th.
    • Saturday, then the last Friday is always the 28th.

    There are only three special cases. A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)

    Work it out on paper. Don't need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )

    Aaron implemented it in Java.

    -Adam

提交回复
热议问题