Compare Time to Determine if Now is Today

Given the following front matter:

sale_ends = 2017-11-14

Is there a way to determine if now is the same day as sale_ends? I don’t mind exploring more on my own, but I’m not sure if there’s a simple way or if I should start reviewing the Go docs linked from now. Thank you!

I haven’t tried , but you should be able to use time function to convert that sale_ends string to time.Time format, and then .Unix to convert that time and now time to seconds, and then take a difference of those. You can know if the time is already past if the difference is negative/positive. Based on the difference amount, you can also tell if the sale_ends day is the same as today now (which is actually the date the site was last published, not necessarily today).

Related example: https://gohugo.io/functions/unix/#example-time-passed-since-last-modification

Also, I am assuming that you already looked at setting expirydate in the front-matter? If you want to just not publish a post beyond certain date, just use that variable in the front-matter so that you don’t need to do that date math.

With .Date you can easily convert to Unix time for comparison to now (".Date.Unix" “ge” now.Unix), but it looks like you need to convert your field instead of a date parameter, so you could probably do something like {{.Params.sale_end | dateFormat "20060102"}} and use that to compare to now. You’ll have to convert now in whatever date format you choose to match (e.g. {{now.Format "20060102"}}). I think that will work.

I have a bit of code to highlight posts updated within 3 days, hope this will be helpful:

use YearDay is really convenient.

...
 {{ if lt (sub now.YearDay .Lastmod.YearDay) 3 }}
      <span class="last-modified">updated within {{ sub now.YearDay .Lastmod.YearDay }} days</span>
 {{ end }}
...

@tcgriffith

Your solution does not work properly. It all goes haywire when you deal with different years. I was getting negative days for old posts.

This works better (my example displays a bootstrap badge, but the principal is the same):

{{ if lt (sub (now.Unix) (.Lastmod.Unix)) 1209600 }}
    <span class="badge badge-secondary">New</span>
{{ end }}

And note, I believe you have to have enableGitInfo set to true for .Lastmod to work.

That is not entirely correct. .Lastmod takes the date as follows:

  • If lastmod is not set, and .GitInfo feature is disabled, the front matter date field will be used.
  • If lastmod is not set, and .GitInfo feature is enabled, .GitInfo.AuthorDate will be used instead.