<pre><code>package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now().AddDate(0, -5, 0).Format("January 2006"), -5)
fmt.Println(time.Now().AddDate(0, -4, 0).Format("January 2006"), -4)
fmt.Println(time.Now().AddDate(0, -3, 0).Format("January 2006"), -3)
fmt.Println(time.Now().AddDate(0, -2, 0).Format("January 2006"), -2)
fmt.Println(time.Now().AddDate(0, -1, 0).Format("January 2006"), -1)
fmt.Println(time.Now().AddDate(0, 0, 0).Format("January 2006"), 0)
}
</code></pre>
<p>this code skips february.</p>
<hr/>**评论:**<br/><br/>igowen: <pre><p>this is the intended behavior. today is June 29; if you look at the code for AddDate():</p>
<p><a href="https://golang.org/src/time/time.go?s=19687:19746#L645" rel="nofollow">https://golang.org/src/time/time.go?s=19687:19746#L645</a></p>
<p>you will see that when you subtract 4 months from June 29, it constructs the date February 29. this date then gets normalized to March 1, since February 29 doesn't exist in 2015.</p></pre>jfred: <pre><p>There is no 'Feb 29th' this year, so the date is rolling over to the next month. If you print the date as well the output might make a little more sense.</p>
<pre><code>...Format("January 2, 2006")
</code></pre>
<p>Or just wait and run it again in 2 days</p></pre>cantm0ve: <pre><p>oh ok, i didn't know that thanks </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传