Go语言程序获取当前日期时间的各个组成部分


在本文中,我们将学习如何在 Go 语言中使用各种内部时间函数来获取当前日期时间的各个组成部分。现在,我们将使用 time 包中的函数获取当前日期时间,并使用各个组成部分作为方法来计算日期时间的各个组成部分。

语法

func Now() Time

Now() 函数定义在 time 包中。此函数生成当前本地时间。要使用此函数,我们必须首先在程序中导入 time 包。

time.Month()

此方法属于 time 包。它用于获取当前月份作为 time.Month 值。

time.Day()

此方法是 time 包的一部分。它用于获取当前日期作为 time.Day 值。

time.Hour()

此方法是 time 包的一部分。它用于获取当前小时作为 time.Hour 值。

time.Minute()

此方法是 time 包的一部分。它用于获取当前分钟作为 time.Minute 值。

time.Second()

此方法是 time 包的一部分。它用于获取当前秒作为 time.Second 值。

使用各个组成部分

在本例中,我们将编写一个 Go 语言程序来使用各个组成部分获取当前时间。这些组成部分将与存储在变量中的当前时间一起使用。

算法

  • 步骤 1 - 在程序中导入所需的包

  • 步骤 2 - 创建一个主函数

  • 步骤 3 - 在主函数中,使用内置函数获取当前时间

  • 步骤 4 - 从当前时间中使用内部函数检索各个组成部分

  • 步骤 5 - 使用 fmt 包中的 Printf 函数打印这些组成部分

示例

在下面的 Go 语言程序中,我们将了解如何使用各个组成部分获取当前日期时间的各个组成部分

package main

import (
   "fmt"
   "time"
)

func main() {
   currentTime := time.Now() 
          
    
   year := currentTime.Year()
   month := currentTime.Month()
   day := currentTime.Day()
   hour := currentTime.Hour()
   minute := currentTime.Minute()
   second := currentTime.Second()
   fmt.Println("The individual components can be represented as:")

   fmt.Printf("Year: %d\n", year)
   fmt.Printf("Month: %d\n", month)
   fmt.Printf("Day: %d\n", day)
   fmt.Printf("Hour: %d\n", hour)
   fmt.Printf("Minute: %d\n", minute)
   fmt.Printf("Second: %d\n", second)
}

输出

The individual components can be represented as:
Year: 2023
Month: 4
Day: 3
Hour: 4
Minute: 31
Second: 59

在当前时间上使用 Date 和 Clock 方法

在这种方法中,我们将编写一个 Go 语言程序,使用 Date 和 Clock 方法在使用 Now 方法计算的当前时间上获取当前日期时间的各个组成部分。

算法

  • 步骤 1 - 此程序在程序中导入 fmt 和 time 包,其中 fmt 帮助格式化输入和输出,time 帮助获取时间

  • 步骤 2 - 创建一个主函数,在其中使用 time 包中的 Now 函数计算 current_time

  • 步骤 3 - 获取当前时间上的 Date、Clock 和 Zone 方法的各个组成部分

  • 步骤 4 - 使用 fmt 包中的 Println 函数在控制台上打印年份、月份、日期、小时、分钟、秒和时区。

  • 步骤 5 - 使用 %d 格式说明符在控制台上打印数字。

示例

下面的 Go 语言程序说明了如何使用 Date 和 Clock 方法在当前时间上获取当前日期时间的各个组成部分

package main

import (
   "fmt"
   "time"
)
func main() {
	
   current_time := time.Now()
	
   year, month, day := current_time.Date()
   hour, minute, second := current_time.Clock()
   zone, _ := current_time.Zone()
	
   fmt.Printf("Year: %d\n", year)
   fmt.Printf("Month: %d\n", month)
   fmt.Printf("Day: %d\n", day)
   fmt.Printf("Hour: %d\n", hour)
   fmt.Printf("Minute: %d\n", minute)
   fmt.Printf("Second: %d\n", second)
   fmt.Printf("Timezone: %s\n", zone)
}

输出

Year: 2023
Month: 4
Day: 3
Hour: 4
Minute: 33
Second: 6
Timezone: UTC

结论

我们编译并执行了使用两个示例获取当前日期时间的各个组成部分的程序。在本例中,我们使用了与计算出的当前时间一起使用的内置组件,在第二个示例中,我们使用了 Date 和 Clock 方法来获取日期和时间的各个组成部分。

更新于: 2023年4月3日

152 次查看

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.