基本时间操作

首先,我们来看一些基本的时间操作。

time.Now()time.Time
package main
import (
    "fmt"
    "time"
)
func main() {
    currentTime := time.Now()
    fmt.Println("Current time is", currentTime)
}

输出结果类似于:

Current time is 2022-05-24 11:07:36.710239 +0800 CST m=+0.000149139

time.Format()
package main
import (
    "fmt"
    "time"
)
func main() {
    currentTime := time.Now()
    fmt.Println("Current time is", currentTime.Format("2006-01-02 15:04:05"))
}

输出结果类似于:

Current time is 2022-05-24 11:08:11

"2006-01-02 15:04:05"
  • 2006 表示年份
  • 01 表示月份
  • 02 表示日期
  • 15 表示小时
  • 04 表示分钟
  • 05 表示秒钟

需要注意的是,格式字符串中的数字必须是这些特定的数字,否则会出现错误。

time.Parse()time.Time
package main
import (
    "fmt"
    "time"
)
func main() {
    timeStr := "2022-05-24 11:08:11"
    parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr)
    fmt.Println("Parsed time is", parsedTime)
}

输出结果类似于:

Parsed time is 2023-05-24 11:08:11 +0000 UTC

特定日期时间格式

在上面的示例中,我们使用了一个特定的日期格式字符串。下面列举一些常用的特定日期时间格式:

2006-01-0215:04:052006-01-02 15:04:0501/02/06 3:04 PM02/01/2006 15:04

自定义日期时间格式

如果上面提供的特定日期时间格式无法满足我们的需求,我们可以自定义日期时间格式。

package main
import (
    "fmt"
    "time"
)
func main() {
    currentTime := time.Now()
    customFormat := "2006年01月02日 15点04分05秒"
    fmt.Println("Current time is", currentTime.Format(customFormat))
}

输出结果类似于

Current time is 2023年05月24日 11点14分53秒

解析不同格式的日期时间字符串

有时候我们会遇到各种各样的日期时间字符串格式,这时我们需要能够正确地解析它们

package main
import (
    "fmt"
    "time"
)
func main() {
    timeStr := "2023-05-24 11:08:11"
    parsedTime, _ := time.Parse("2006-01-02 15:04:05", timeStr)
    fmt.Println("Parsed time is", parsedTime)
    timeStr2 := "05/24/22 11:08 AM"
    parsedTime2, _ := time.Parse("01/02/06 3:04 PM", timeStr2)
    fmt.Println("Parsed time is", parsedTime2)
    timeStr3 := "2023年05月24日 11点14分53秒"
    parsedTime3, _ := time.Parse("2006年01月02日 15点04分05秒", timeStr3)
    fmt.Println("Parsed time is", parsedTime3)
}

获取指定日期时间

time.Date()
package main
import (
    "fmt"
    "time"
)
func main() {
    specTime := time.Date(2023, 5, 24, 12, 0, 0, 0, time.Local)
    fmt.Println("Specified time is", specTime.Format("2006-01-02 15:04:05"))
}

输出结果类似于:

Specified time is 2022-05-24 12:00:00

您可能感兴趣的文章: