[Go] Detailed explanation of the commonly used functions and types in the time package

Table of contents

Commonly used functions

time.Now()

set time zone

 Get the 0 o'clock of the previous day of the current time

time addition and subtraction


Commonly used functions

The Go language timepackage provides date and time processing functions, allowing you to perform time-related operations in the program, including obtaining the current time, formatting time, parsing time, calculating time intervals, etc.

Here are timesome commonly used functions and types in the package:

  1. time.Now() Function: Returns the current local time.
  2. time.Parse(layout, value string) Function: Parses a formatted time string into a  time.Time typed value.
  3. time.Format(layout string) Method: Format a time as a string with the specified layout.
  4. time.Duration Type: Indicates the time interval, with nanoseconds as the basic unit.
  5. time.Sleep(duration) Function: Pauses the execution of the program for a period of time.

Here are some commonly used examples:

package main

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前时间
	now := time.Now()
	fmt.Println("当前时间:", now)

	// 格式化时间为字符串
	timeStr := now.Format("2006-01-02 15:04:05")
	fmt.Println("格式化后的时间:", timeStr)

	// 解析字符串为时间
	parseTime, _ := time.Parse("2006-01-02", "2023-08-04")
	fmt.Println("解析后的时间:", parseTime)

	// 计算时间间隔
	duration := time.Since(now)
	fmt.Println("时间间隔:", duration)

	// 暂停程序执行一段时间
	time.Sleep(2 * time.Second)
	fmt.Println("2秒后的时间:", time.Now())
}

time.Now()

package main

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前时间
	now := time.Now()
	fmt.Println("当前时间:", now)

	year := now.Year()     //年
	month := now.Month()   //月
	day := now.Day()       //日
	hour := now.Hour()     //小时
	minute := now.Minute() //分钟
	second := now.Second() //秒
	fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

set time zone

 Get the 0 o'clock of the previous day of the current time

    // 获取当前日期
    t := time.Now().UTC()
    // 计算前一天的日期
    t = t.AddDate(0, 0, -1)
    // 设置时间为零点
    t = time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location())
    // 输出结果
    fmt.Println(t)

time addition and subtraction

In the Go language, you can use timethe package to add and subtract time. time.DurationThe type represents the time interval, and the time can be added and subtracted through addition and subtraction operations.

Here are some common time addition and subtraction examples:

package main

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前时间
	now := time.Now()
	fmt.Println("当前时间:", now)

	// 加上一段时间间隔
	afterOneHour := now.Add(1 * time.Hour)
	fmt.Println("一小时后的时间:", afterOneHour)

	// 减去一段时间间隔
	beforeOneDay := now.Add(-24 * time.Hour)
	fmt.Println("一天前的时间:", beforeOneDay)

	// 计算两个时间点之间的时间间隔
	duration := afterOneHour.Sub(beforeOneDay)
	fmt.Println("时间间隔:", duration)

	// 执行相对时间的加减运算
	tenMinutesLater := now.Add(10 * time.Minute)
	fiveHoursEarlier := tenMinutesLater.Add(-5 * time.Hour)
	fmt.Println("十分钟后五小时前的时间:", fiveHoursEarlier)
}

 In the example, we use Add()the method to add the time, you can pass in a positive number to indicate adding a period of time, or pass in a negative number to indicate subtracting a period of time. Sub()The time interval between two time points can be calculated using the method.

It should be noted that the unit of addition and subtraction must be time.Durationof type. Commonly used time units are nanoseconds ( time.Nanosecond), microseconds ( time.Microsecond), milliseconds ( time.Millisecond), seconds ( ) time.Second, minutes ( time.Minute), hours ( time.Hour), etc. The time interval of a specific unit can be obtained through multiplication and division operations.

In addition, you can also use time.AddDate()the method to add and subtract the year, month, and day, and select the appropriate method to add and subtract the time according to your needs.

Guess you like

Origin blog.csdn.net/fanjufei123456/article/details/129789589