日期格式化对于JavaScript日期

huangapple go评论109阅读模式
英文:

Date.Format for javascript date

问题

我有一个从appengine数据存储加载的数组,其中包含以下结构:

struct {
    Date         time.Time
    PostedSample int
}

我想将其输出到html/template中,以便用于<a href="https://developers.google.com/chart/interactive/docs/gallery/annotatedtimeline#Data_Format">Google Visualization Time Line</a>。首先,我尝试在模板中直接使用{{.Date.Format &quot;new Date(2006,1,2,15,4,5)&quot;}}来格式化日期,但是html/template会对此进行转义,因此它在html源代码中显示为带引号的字符串。然后,我尝试将日期格式化为[]struct{Date template.JS; Value template.JS},使用表达式template.JS(m.Date.Format(&quot;new Date(2006,1,2,15,4,5)&quot;)),这几乎可以工作,只是月份减少了一个,因为JavaScript中的一月是0。我可以让模板生成日期参数的JSON,并编写JavaScript将其转换为Date对象,或者使用Go代码调整模板输出。请分享一个更优雅的解决方案。谢谢。

英文:

I have an array of

struct {
    Date         time.Time
    PostedSample int
}

loaded from the appengine datastore which I want to output in a html/template for the <a href="https://developers.google.com/chart/interactive/docs/gallery/annotatedtimeline#Data_Format">Google Visualization Time Line</a>. First I tried formatting the Date directly in the template with {{.Date.Format &quot;new Date(2006,1,2,15,4,5)&quot;}} but html/template escapes this so it appears as a quoted string in the html source. I then tried formatting the date into a []struct{Date template.JS; Value template.JS} with the expression template.JS(m.Date.Format(&quot;new Date(2006,1,2,15,4,5)&quot;)) which almost works except the month is off by one, javascript wants January as 0. I could have the template generate a json of date parameters and write javascript turn that into Date objects or have go code which adjusts the template output. Please share a more elegant solution. Thank you.

答案1

得分: 1

你不需要在模板中添加格式化函数。

你可以像这样使用你的结构体:

{{.Date.Format "Mon 2 Jan 2006"}}

解决方案可能是这样的:

var date = new Date(parseInt({{.Date.Nanosecond }} /1000));

英文:

You don't need to add a format function to the templates.

You can use your struct like so:

{{.Date.Format &quot;Mon 2 Jan 2006&quot;}}

The solution might be something like this:

var date = new Date(parseInt({{.Date.Nanosecond }} /1000));

huangapple
  • 本文由 发表于 2013年6月2日 11:06:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/16879393.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定