英文:
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 "new Date(2006,1,2,15,4,5)"}}
来格式化日期,但是html/template会对此进行转义,因此它在html源代码中显示为带引号的字符串。然后,我尝试将日期格式化为[]struct{Date template.JS; Value template.JS}
,使用表达式template.JS(m.Date.Format("new Date(2006,1,2,15,4,5)"))
,这几乎可以工作,只是月份减少了一个,因为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 "new Date(2006,1,2,15,4,5)"}}
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("new Date(2006,1,2,15,4,5)"))
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 "Mon 2 Jan 2006"}}
The solution might be something like this:
var date = new Date(parseInt({{.Date.Nanosecond }} /1000));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论