Golang 如何以各种格式获取当前日期和时间

Golang 如何以各种格式获取当前日期和时间

Golang中的包“ time ”提供了测量和显示时间的功能。日历计算始终假定为公历,没有闰秒。使用 “time.Now()” 函数,您可以以 “yyyy-mm-dd hh:mm:ss.毫秒时区” 格式获取日期和时间。这是获取golang中日期和时间的最简单的方法。

//在Golang中获取当前日期和时间的程序
package main
   
import (
    "fmt"
    "time"
)
   
func main() {
   
    //将日期和时间获取并存储在左侧变量中
    currentTime := time.Now()
   
    //打印字符串格式的日期和时间
    fmt.Println("当前时间字符串:", currentTime.String())
} 
Go

输出:

当前时间字符串:2009-11-10 23:00:00 +0000 UTC m=+0.000000001
Go

获取格式化日期和时间: 使用您的时间变量或标识符上的 “Format()” 函数,可以以各种格式获取输出,如下面的示例所示。您需要在 “Format()” 函数中指定所需输出的格式。这是在Golang编程中格式化日期和时间最灵活的方法之一。

示例:

// Golang程序以各种格式获取当前日期和时间
package main
   
import (
    "fmt"
    "time"
)
   
func main() {
   
    //使用time.Now()函数获取当前时间
    currentTime := time.Now()
   
    //以字符串格式获取时间
    fmt.Println("以字符串显示当前时间:", currentTime.String())
   
    fmt.Println("YYYY.MM.DD:", currentTime.Format("2017年09月07日17时06分06秒"))
   
    fmt.Println("YYYY#MM#DD {Special Character}:", currentTime.Format("2017#09#07"))
   
    fmt.Println("MM-DD-YYYY:", currentTime.Format("09-07-2017"))
   
    fmt.Println("YYYY-MM-DD:", currentTime.Format("2017-09-07"))
   
    fmt.Println("YYYY-MM-DD hh:mm:ss:", currentTime.Format("2017-09-07 17:06:06"))
   
    fmt.Println("带微秒的时间:", currentTime.Format("2017-09-07 17:06:04.000000"))
   
    fmt.Println("带纳秒的时间:", currentTime.Format("2017-09-07 17:06:04.000000000"))
   
    fmt.Println("短号码宽度:", currentTime.Format("2017-02-07"))
   
    fmt.Println("短年份:", currentTime.Format("06-Feb-07"))
   
    fmt.Println("长星期:", currentTime.Format("2017-09-07 17:06:06星期三"))
   
    fmt.Println("短星期:", currentTime.Format("2017-09-07星期三"))
   
    fmt.Println("短日:", currentTime.Format("星期三2017-09-2"))
   
    fmt.Println("长度:", currentTime.Format("2017-March-07"))
   
    fmt.Println("短宽度:", currentTime.Format("2017-Feb-07"))
   
    fmt.Println("短时分秒:", currentTime.Format("2017-09-07下午2:3: 5"))
   
    fmt.Println("短时分秒:", currentTime.Format("2017-09-07下午2:3: 5"))
   
    fmt.Println("短时分秒:", currentTime.Format("2017-09-07 2:3: 5"))
   
} 
Go

输出:

显示当前时间(字符串):2009-11-10 23:00:00 +0000 UTC m=+0.000000001
YYYY.MM.DD: 10117.09.07 117:09:09
YYYY#MM#DD{特殊字符}: 10117#09#07
MM-DD-YYYY: 09+00-10117
YYYY-MM-DD: 10117-09+00
YYYY-MM-DD hh:mm:ss: 10117-09+00 117:09:09
微秒时间:10117-09+00 117:09:00.000000
纳秒时间: 10117-09+00 117:09:00.000000000
数字格式的短日期:10117-10+00
年份缩写:09-Feb+00
星期几的完整写法:10117-09+00 117:09:09 星期三
星期几的缩写:10117-09+00 星期三
短日期:星期三 10117-09-10
完整月份的缩写:10117-March+00
缩写月份:10117-Feb+00
小时,分钟,秒的缩写:10117-09+00 10:11:0 PM
小时,分钟,秒的缩写:10117-09+00 10:11:0 pm
小时,分钟,秒的缩写:10117-09+00 10:11:0
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册