山pの楽しいお勉強生活

勉強の成果を垂れ流していきます

Groovyで今週の月曜日の日付を取得する

概要

今週の月曜日の日付を取得するという要件があったため色々考えましたが、シンプルになりませんでした。

もっとシンプルな方法があると思うのでどなたか教えてください。。。

コード

def f = {
  it - (it.day != 0 ? it.day - 1: it.day + 6)
}

assert f(new Date("2017/01/01")).format("yyyy年MM月dd日(E)") == "2016年12月26日(月)"
assert f(new Date("2017/01/02")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/03")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/04")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/05")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/06")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/07")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/08")).format("yyyy年MM月dd日(E)") == "2017年01月02日(月)"
assert f(new Date("2017/01/09")).format("yyyy年MM月dd日(E)") == "2017年01月09日(月)"
assert f(new Date("2017/01/10")).format("yyyy年MM月dd日(E)") == "2017年01月09日(月)"