在本教程中,您将看到 time 包。在之前的教程中,我们讨论了 Go 源代码中包含的 main、fmt、math 等包,以帮助用户轻松高效地编写代码。本教程提供有关 time 包的信息,以及如何在 Go 程序中使用它等。

Go 编程语言支持 time 和 duration 包。通过 import “time” 将该包导入到源代码中。这个内置包使用户能够查找时间的关联组件,例如:

在 Go 编程语言中,time 包提供了使用 time.Now() 确定当前时间的功能。
T := time.Now() //local time
上述语法打印 Golang 中的当前时间或本地时间。以相同的方式,也可以通过在上述语法后附加 .UTC() 来确定 UTC 时间。
T : = time.Now().UTC() //UTC time
package main
import (
"fmt"
"time" // imported time package
)
func main() {
t := time.Now() //local time or current time
T := time.Now().UTC() //UTC time
fmt.Println(t)
fmt.Println(T)
//fmt.Println(time.Now()) 2022-01-06 04:22:52.659567558 +0000 UTC m=+0.000115532
}
输出
2022-01-06 04:27:23.440296468 +0000 UTC m=+0.000059050 2022-01-06 04:27:23.440296614 +0000 UTC
注意:您可以从输出中推断出,当调用 time.Now() 或 time.Now().UTC() 时,还会提供当前日期,例如 2022-01-06(年-月-日)格式。
Go 标准库的 time 包提供了一个特定函数来为特定日期创建时间。使用的 Date() 函数用于在时间中查找日期。输出形式为 yyyy-mm-dd hh:mm:ss + nsec nanoseconds
func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
调用日期函数使用的格式或语法是
time.Date()
让我们看一个例子

package main
import (
"fmt"
"time"
)
func main() {
fmt.Println("Current time ")
t := time.Now() //current time
fmt.Println(t)
fmt.Println("................")
fmt.Println("Current time with UTC")
T := time.Now().UTC() //UTC time
fmt.Println(T)
fmt.Println("................")
fmt.Println(" time created for a day")
//takes a year, month, day, hour, minute, second, nanosecond, and location
Created_Day := time.Date(2016, time.August, 18, 23, 15, 8, 4, time.UTC)
fmt.Println(Created_Day )
}
输出
Current time 2022-01-06 05:03:37.427431402 +0000 UTC m=+0.000048473 ................ Current time with UTC 2022-01-06 05:03:37.427494967 +0000 UTC ................ time created for a day 2016-08-18 23:15:08.000000004 +0000 UTC
在 Go 编程语言中,时间使用下面给出的方法进行格式化。使用 Format() 函数,可以在括号之间传递所需的输出格式,该格式将显示在控制台中。Format() 的优点之一是它有助于以更灵活的方式格式化日期和时间包
time.Format()
package main
import (
"fmt"
"time"
)
func main() {
// time.Now() function gives the current time
currentTime := time.Now()
// getting the time in string format
fmt.Println("Show Current Time in String: ", currentTime.String())
fmt.Println("YYYY.MM.DD : ", currentTime.Format("2022-01-06 04:27:23.440296468 "))
fmt.Println("YYYY#MM#DD {Special Character} : ", currentTime.Format("2022#01#06"))
fmt.Println("MM-DD-YYYY : ", currentTime.Format("06-07-2017"))
fmt.Println("YYYY-MM-DD : ", currentTime.Format("2022-09-07"))
fmt.Println("YYYY-MM-DD hh:mm:ss : ", currentTime.Format("2022-09-07 17:06:06"))
fmt.Println("Time with MicroSeconds: ", currentTime.Format("2022-09-07 17:06:04.000000"))
fmt.Println("Time with NanoSeconds: ", currentTime.Format("2022-09-07 17:06:04.000000000"))
fmt.Println("ShortNum Width : ", currentTime.Format("2022-02-07"))
fmt.Println("ShortYear : ", currentTime.Format("06-Feb-07"))
fmt.Println("LongWeekDay : ", currentTime.Format("2022-09-07 17:06:06 Wednesday"))
fmt.Println("ShortWeek Day : ", currentTime.Format("2022-09-07 Wed"))
fmt.Println("ShortDay : ", currentTime.Format("Wed 2022-09-2"))
fmt.Println("LongWidth : ", currentTime.Format("2022-March-07"))
fmt.Println("ShortWidth : ", currentTime.Format("2017-Feb-07"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 PM"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5 pm"))
fmt.Println("Short Hour Minute Second: ", currentTime.Format("2017-09-07 2:3:5"))
}
输出
Show Current Time in String: 2009-11-10 23:00:00 +0000 UTC m=+0.000000001 YYYY.MM.DD : 101010-11-09 00:107:1011.001096068 YYYY#MM#DD {Special Character} : 101010#11#09 MM-DD-YYYY : 09+00-10117 YYYY-MM-DD : 101010-09+00 YYYY-MM-DD hh:mm:ss : 101010-09+00 117:09:09 Time with MicroSeconds: 101010-09+00 117:09:00.000000 Time with NanoSeconds: 101010-09+00 117:09:00.000000000 ShortNum Width : 101010-10+00 ShortYear : 09-Feb+00 LongWeekDay : 101010-09+00 117:09:09 Wednesday ShortWeek Day : 101010-09+00 Wed ShortDay : Wed 101010-09-10
time.Parse() 函数将时间字符串和布局作为输入来创建新时间。Parse() 函数解析格式化的字符串并返回它所表示的时间值。
解析语法
func Parse(layout, value string) (Time, error)
函数 parse() 分别接受两个参数
示例
package main
import (
"fmt"
"time"
)
func main() {
//Parse YYYY-MM-DD
timeT, _ := time.Parse("2006-01-02", "2020-01-29")
fmt.Println(timeT)
//Parse YY-MM-DD
timeT, _ = time.Parse("06-01-02", "20-01-29")
fmt.Println(timeT)
//Parse YYYY-#{MonthName}-DD
timeT, _ = time.Parse("2006-Jan-02", "2020-Jan-29")
fmt.Println(timeT)
//Parse YYYY-#{MonthName}-DD WeekDay HH:MM:SS
timeT, _ = time.Parse("2006-Jan-02 Monday 03:04:05", "2020-Jan-29 Wednesday 12:19:25")
fmt.Println(timeT)
//Parse YYYY-#{MonthName}-DD WeekDay HH:MM:SS PM Timezone TimezoneOffset
timeT, _ = time.Parse("2006-Jan-02 Monday 03:04:05 PM MST -07:00", "2020-Jan-29 Wednesday 12:19:25 AM IST +05:30")
fmt.Println(timeT)
}
输出
2020-01-29 00:00:00 +0000 UTC 2020-01-29 00:00:00 +0000 UTC 2020-01-29 00:00:00 +0000 UTC 2020-01-29 12:19:25 +0000 UTC 2020-01-29 00:19:25 +0530 IST
在 time 包中,有几个算术操作作为辅助函数可用,用于设置时间和持续时间。
在 Add() 函数中有两种可能的格式,它们是 time.Add() 和 time.AddDate()
让我们通过一个例子来看看这些格式与 Golang 中的时间一起使用时会发生什么
package main
import (
"fmt"
"time"
)
func main() {
T := time.Now().UTC() //UTC time
timeInFiveMin := T.Add(time.Minute * 5) //add 5 minutes more
timeInFiveMin1 := T.Add(time.Minute * 10) //add 10 minutes more
timeInFiveMin2 := T.Add(-time.Minute * 10) // - sign indicate 10 min ago
fmt.Println(T)
fmt.Println( timeInFiveMin)
fmt.Println(timeInFiveMin1)
fmt.Println(timeInFiveMin2)
}
输出
2022-01-06 09:14:14.228317512 +0000 UTC 2022-01-06 09:19:14.228317512 +0000 UTC 2022-01-06 09:24:14.228317512 +0000 UTC 2022-01-06 09:04:14.228317512 +0000 UTC
package main
import (
"fmt"
"time"
)
func main() {
T := time.Now().UTC() //UTC time
// adds years, months, and days
inOneMonth := T.AddDate(0, 1, 0)
// inOneMonth is 1 month in the future
threeDaysAgo := T.AddDate(0, 0, -3)
// twoDaysAgo is 2 days in the past
fmt.Println(T)
fmt.Println( inOneMonth)
fmt.Println(threeDaysAgo )
}
输出
2022-01-06 09:19:44.567410824 +0000 UTC 2022-02-06 09:19:44.567410824 +0000 UTC 2022-01-03 09:19:44.567410824 +0000 UTC
时间中的 sub 函数允许比较两个时间之间的差异。
package main
import (
"fmt"
"time"
)
func main() {
T := time.Now().UTC() //UTC time
start := time.Date(2022, 2, 1, 3, 0, 0, 0, time.UTC)
end := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC)
difference := end.Sub(start)
fmt.Println(T)
fmt.Println( start )
fmt.Println(end )
fmt.Printf("difference = %v\n", difference)
}
输出
2022-01-06 09:29:22.849925449 +0000 UTC 2022-02-01 03:00:00 +0000 UTC 2021-02-01 12:00:00 +0000 UTC difference = -8751h0m0s
Golang 中的一些比较函数是
使用的格式如下:After() 函数确定时间瞬间 T 是否在 a 之后。返回类型是布尔值。
func (T Time) After(a Time) bool
package main
import (
"fmt"
"time"
)
func main() {
year2023 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
year2022 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
isYear2023AfterYear2022 := year2023.After(year2022) // false
isYear2022AfterYear2023 := year2022.After(year2023) // true
fmt.Printf("year2023.After(year2022) = %v\n", isYear2023AfterYear2022)
fmt.Printf("year2022.After(year2023)) = %v\n", isYear2022AfterYear2023)
}
输出
year2023.After(year2022) = false year2022.After(year2023)) = true Program exited.
使用的格式如下:Before() 函数确定时间瞬间 T 是否在 a 之前。返回类型是布尔值。
func (T Time) Before(a Time) bool
package main
import (
"fmt"
"time"
)
func main() {
year2023 := time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)
year2022 := time.Date(3000, 1, 1, 0, 0, 0, 0, time.UTC)
isYear2023BeforeYear2022 := year2023.Before(year2022) // true
isYear2022BeforeYear2023 := year2022.Before(year2023) // false
fmt.Printf("year2023.Before(year2022) = %v\n", isYear2023BeforeYear2022)
fmt.Printf("year2022.Before(year2023)) = %v\n", isYear2022BeforeYear2023)
}
输出
year2023.Before(year2022) = true year2022.Before(year2023)) = false Program exited.
用于检查两个时间实例是否相等的格式如下,Equal() 函数确定时间瞬间 T 是否等于时间 a。返回类型是布尔值。
func (T Time) Equal(a Time) bool
package main
import (
"fmt"
"time"
)
func main() {
first := time.Date(2020, 2, 1, 3, 0, 0, 0, time.UTC)
second := time.Date(2021, 2, 1, 12, 0, 0, 0, time.UTC)
equal := first.Equal(second)
fmt.Println(equal)
// equal is true if the both times refer to the same instant
// two times are equal even if they are in different locations
}
输出
false
// Go offers extensive support for times and durations;
// here are some examples.
package main
import (
"fmt"
"time"
)
func main() {
print := fmt.Println
// We'll start by getting the current time.
T := time.Now()
print(T)
// You can build a `time` struct by providing the
// year, month, day, etc. Times are always associated
// with a `Location`, i.e. time zone.
Time := time.Date(
2016, 07, 18, 15, 00, 58, 651387237, time.UTC)
print(Time)
// You can extract the various components of the time
// value as expected.
print(Time.Year())
print(Time.Month())
print(Time.Day())
print(Time.Hour())
print(Time.Minute())
print(Time.Second())
print(Time.Nanosecond())
print(Time.Location())
// The Monday-Sunday `Weekday` is also available.
print(Time.Weekday())
// These methods compare two times, testing if the
// first occurs before, after, or at the same time
// as the second, respectively.
print(Time.Before(T))
print(Time.After(T))
print(Time.Equal(T))
// The `Sub` methods returns a `Duration` representing
// the interval between two times.
difference := T.Sub(Time)
print(difference)
// We can compute the length of the duration in
// various units.
print(difference.Hours())
print(difference.Minutes())
print(difference.Seconds())
print(difference.Nanoseconds())
// You can use `Add` to advance a time by a given
// duration, or with a `-` to move backwards by a
// duration.
print(Time.Add(difference))
print(Time.Add(-difference))
}
输出
2022-01-06 12:00:58.741830042 +0000 UTC m=+0.000049115 2016-07-18 15:00:58.651387237 +0000 UTC 2016 July 18 15 0 58 651387237 UTC Monday true false false 47949h0m0.090442805s 47949.000025123 2.87694000150738e+06 1.726164000904428e+08 172616400090442805 2022-01-06 12:00:58.741830042 +0000 UTC 2011-01-28 18:00:58.560944432 +0000 UTC
分析每个函数及其对应的输出。Go 中的 time 包非常高效、灵活,易于使用和理解。