How to render correct datetime in hugo post?

Viewed 1718

I created a post using hugo new posts/mypost.md and it created mypost.md for me with header toml configuration like that

toml config

But, when i run on server (local), the datetime rendered wrong like: enter image description here

How can I fix that? Thanks in advance!

5 Answers

This is how I got it to work:

Add your date format in config.toml

[params]
    dateFormat = "02 Jan 2006"

Your post should contain the date in its front-matter:

---
date: "2020-12-23T15:21:54+05:30"
...
---

Use the format in your layout:

<div>{{ .Params.date.Format .Site.Params.dateFormat }}</div>

Note: Please DO NOT change the numbers in the date format. It must be 02 for day, Jan for month, 2006 for year, etc. check this for more details.

Check also Hugo 0.87 (Aug. 2021, two years later), which comes with:

  • a timezone

  • a timedate format

    {{ time.Format "Monday, Jan 2, 2006" "2015-01-21" }} 
    → 
    "Wednesday, Jan 21, 2015"
    

Note that since Hugo 0.87.0, time.Format will return a localized string for the current language.

  • Date/time formatting layouts

    {{ .Date | time.Format ":date_long" }}
    

The full list of custom layouts with examples for English:

:date_full => Wednesday, June 6, 2018

:date_long => June 6, 2018

:date_medium => Jun 6, 2018

:date_short => 6/6/18

:time_full => 2:09:37 am UTC

:time_long => 2:09:37 am UTC

:time_medium => 2:09:37 am

:time_short => 2:09 am

You need to set dateformat in file config.toml at 2.1.2006 (any proper format, ensure 2, Jan, 2006).
This link save my day

In Hugo v0.95.0 (released 16 Mar 2022), it should be

[params]
    date_format = "02 Jan 2006"

with

---
date: 2022-03-18T21:10:00+07:00
---

in the post front matter, where double quote marks are not necessary. I used Ananke theme.

Setting the date_format in the config file seems weird to me. I would set the following in the config file:

defaultContentLanguage: nl
languageCode: nl_NL

These are variables that do NOT go into params, but on the root level of the config file. When you have these you can simply call:

{{ .Date | time.Format ":date_long" }} 

or... if you need another format:

{{ .Date | time.Format ":date_medium" }}

The date will be formatted in your language.

Related