使用sub方法进行日期解析

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

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"))

}

huangapple
  • 本文由 发表于 2013年4月17日 05:02:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/16047012.html
匿名

发表评论

匿名网友

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

确定