Date last Monday

I’m calling an API for JSON and you pass the from and to date to it to bring back data. I’d like to have the from date as the previous Monday, is there a way to do this?

for instance, today is Wednesday the 13th. I’d like to work out Monday the 11th.

Maybe AddDate can contain a variable and we can find the weekday number for today?

{ $d := “2022-07-13” | time.AsTime }}
{ $weekday := time.Format(something for weekday)
{{ $d.AddDate 0 0 -{{$weekday}} | time.Format “2006-01-02” }} → 2022-07-11

layouts/partials/last-monday.html

{{ $d := time.AsTime . }}
{{ $lastMonday := 0 }}
{{ with int $d.Weekday }}
  {{ $lastMonday = $d.AddDate 0 0 (int (sub 1 $d.Weekday)) }}
{{ else }}
  {{ $lastMonday = $d.AddDate 0 0 -6 }}
{{ end }}
{{ return ($lastMonday | time.Format "2006-01-02") }}

Call it with

{{ partial "last-monday.html" "2022-07-17" }}
5 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.