获取时间戳的年份的第一天和最后一天。

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

Get the first and last day of a year from a timestamp

问题

给定一个时间对象,t := time.Now(),有没有办法获取该年份的第一天和最后一天的时间戳?

我可以这样做:d := t.YearDay() 来获取一年中的天数,然后使用 t.AddDate(0, 0, -d) 来获取该年的开始时间,使用 t.AddDate(0, 0, 365-d) 来获取该年的结束时间,但这种方法似乎不够灵活,无法处理闰年等情况。

英文:

Given a time object, t := time.Now(), is there a way I could get a timestamp for the first and last days of that year?

I could do something like d := t.YearDay() to get the number of days through the year, and then t.AddDate(0, 0, -d) to get the start of the year, and t.AddDate(0, 0, 365-d) to get the end of the year, but that seems to brittle as it doesn't deal with leap years etc.

答案1

得分: 7

你可以使用Time结构对象,并使用time.Date和time.Time.Year函数创建新的Time结构对象。所以,如果当前时间是t := time.Now(),那么UTC时区中今年的最后一天将是lt := time.Date(t.Year(), time.December, 31, 0, 0, 0, 0, time.UTC)

以下是一个示例:

package main

import "fmt"
import "time"

func main() {
    t := time.Now()
    last := time.Date(t.Year(), time.December, 31, 0, 0, 0, 0, time.UTC)
    first := time.Date(t.Year(), time.January, 1, 0, 0, 0, 0, time.UTC)

    fmt.Println("当前时间: ", t)
    fmt.Println("本年度第一天: ", first)
    fmt.Println("本年度最后一天: ", last)
}

你可以在这里运行这个示例:http://play.golang.org/p/jahjd_mi6K

英文:

You can use your Time struct object and create new Time struct object using time.Date and time.Time.Year() functions. So, if current time is t := time.Now() then last day in this year in UTC will be lt := time.Date(t.Year(), time.December, 31, 0, 0, 0, 0, time.UTC)

Here's an example:

package main

import "fmt"
import "time"

func main() {
	t := time.Now()
	last := time.Date(t.Year(), time.December,31, 0, 0, 0, 0, time.UTC)
	first := time.Date(t.Year(), time.January,1, 0, 0, 0, 0, time.UTC)
	
	fmt.Println("Current: ", t)
	fmt.Println("First: ", first)
	fmt.Println("Last: ", last)
	
}

http://play.golang.org/p/jahjd_mi6K

huangapple
  • 本文由 发表于 2015年8月21日 21:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/32140980.html
匿名

发表评论

匿名网友

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

确定