I'm making this simple webserver that can host my blog, but whatever I do; I can not execute a proper formatted time into my html/template.
Here's what I do:
I've created this struct:
type Blogpost struct {
Title string
Content string
Date time.Time
}
Next up I've created this little func that retrieves the blogposts with corresponding title/dates from the Appengine Datastore and return that as a slice:
func GetBlogs(r *http.Request, max int) []Blogpost {
c := appengine.NewContext(r)
q := datastore.NewQuery("Blogpost").Order("-Date").Limit(max)
bp := make([]Blogpost, 0, max)
q.GetAll(c, &bp)
return bp
}
Finally, in the blogHandler I create a slice based on the retrieved data from the Appengine Datastore using:
blogs := GetBlogs(r, 10)
Now when I Execute my template called blog like this, the dates of the blogs are being parsed as default dates:
blog.Execute(w, blogs) // gives dates like: 2013-09-03 16:06:48 +0000 UTC
So, me, being the Golang n00b that I am, would say that a function like the following would give me the result I want
blogs[0].Date = blogs[0].Date.Format("02-01-2006 15:04:05") // Would return like 03-09-2013 16:06:48, at least when you print the formatted date that is.
However that results in a type conflict ofcourse, which I tried to solve using:
blogs[0].Date, _ = time.Parse("02-01-2006 15:04:05", blogs[0].Date.Format("02-01-2006 15:04:05")) // returns once again: 2013-09-03 16:06:48 +0000 UTC
It is probably some n00b thing I oversaw once again, but I just can't see how I can't override a time.Time Type in a slice or at least print it in the format that I want.
While I looking for a similar functionality to simply format and render a time.Time
type in a html/template
, I fortuitously discovered that go's template parser allows methods to be called under certain restrictions when rendering a time.Time
type.
For example;
type Post struct {
Id int
Title string
CreatedOn time.Time
}
// post is a &Post. in my case, I fetched that from a postgresql
// table which has a datetime column for that field and
// value in db is 2015-04-04 20:51:48
template.Execute(w, post)
and it's possible to use that time in a template like below:
<span>{{ .CreatedOn }}</span>
<!-- Outputs: 2015-04-04 20:51:48 +0000 +0000 -->
<span>{{ .CreatedOn.Format "2006 Jan 02" }}</span>
<!-- Outputs: 2015 Apr 04 -->
<span>{{ .CreatedOn.Format "Jan 02, 2006" }}</span>
<!-- Outputs: Apr 04, 2015 -->
<span>{{.CreatedOn.Format "Jan 02, 2006 15:04:05 UTC" }}</span>
<!-- Outputs: Apr 04, 2015 20:51:48 UTC -->
As a note; my go version is go1.4.2 darwin/amd64
Hope it helps others.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With