英文:
Date parsing with sub method
问题
我知道时间包和如何根据日期/时间表示解析模板。我想知道的是如何解析time.Now()的一个月之前的stdLongMonth。
例如:
time.Now() // == 2013年4月
// 输出:2013年3月
换句话说,是否可以使用sub.stdLongMonth()方法解析time.now()?有人可以友好地给出一些示例吗?
英文:
I'm aware of the time package and how you can parse templates based on date/time representation. What I would like to know is how to parse time.Now() one month prior to stdLongMonth.
i.e.
time.Now() // == April, 2013
// Output: March, 2013
In other words, is it possible to parse time.now() with a sub.stdLongMonth() method? Can anyone be kind enough and show some examples?
答案1
得分: 4
例如,
package main
import (
"fmt"
"time"
)
func main() {
y, m, _ := time.Now().Date()
t := time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(t.Format("January, 2006"))
t = time.Date(y, m-1, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(t.Format("January, 2006"))
}
输出:
四月, 2013
三月, 2013
英文:
For example,
package main
import (
"fmt"
"time"
)
func main() {
y, m, _ := time.Now().Date()
t := time.Date(y, m, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(t.Format("January, 2006"))
t = time.Date(y, m-1, 1, 0, 0, 0, 0, time.UTC)
fmt.Println(t.Format("January, 2006"))
}
Output:
April, 2013
March, 2013
答案2
得分: -1
使用time.AddDate()可以使你摆脱时区的考虑:
package main
import (
"fmt"
"time"
)
func main() {
time := time.Now().AddDate(0,-1,0)
fmt.Println(time.Format("January, 2006"))
}
英文:
use time.AddDate() as this will also free you from timezone considerations:
package main
import (
"fmt"
"time"
)
func main() {
time := time.Now().AddDate(0,-1,0)
fmt.Println(time.Format("January, 2006"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论