How to find days elapsed since last post in a listing page?

Just started playing with Hugo yesterday - have zero Go experience. I am building different list pages based on taxonomy. One thing that I couldn’t figure out is how do I get the number of days elapsed since last post - essentially, I am building something like Project Hub template and I want to put a heading at the top saying “Project hasn’t moved since X days” where X is the output of {{ .Now.Sub .Date }}

I am showing the output, but it is too rich - eg: 26h29m52.828673411s - I just need this to be rounded down and show up as 1! Tried with Math module, but it takes only int arguments and not durations.

Went through Go-lang forums and I am able to do this in Go. However, I couldn’t fit any of those ideas into Go Templates.

Ideally, I should be doing this in Javascript since there could be days when nothing is posted and template code will still keep it as 1d. This is more for learning.

PS: Barely a day and I already am in awe of Hugo. Thanks for making such a wonderful tool.

You could maybe give .Date.Format() a try.

Couldn’t figure it out with that! However, also learned about :slight_smile: Anyways, I did this using moment.js using on client side javascript.

You can represent the date as a Unix timestamp, an integer that counts the seconds since the January 1st, 1970. Since both values below are integers we can easily subtract them and divide them by the number of seconds a day has (60 * 60 * 24 = 86400):

{{ div (sub .Now.Unix .Lastmod.Unix) 86400 }}

Remember that this value is static if you want to output it.


Thank you, I was also looking exactly for this. I slightly changed your line into div (sub now.Unix .Lastmod.Unix) 86400 to get it to work with Hugo v0.84

Sorry for resuming this really old thread, but IMHO it would be awesome if someday we may able use something even more clear and straightforward, for example something like this:

{{ $diff := now.Sub .Lastmod }}
Posted {{ $diff.Days }} days ago

You can do this:

{{ $diff := now.Sub .Lastmod }}
Posted {{ math.Round (div $diff.Hours 24) }} days ago

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