go language defragmentation time

Keywords: Go Unix Programming

Time and date are often used in our programming. This paper mainly introduces the basic usage of time package built in Go language.

Import package in Go language

Single line import

import "time"
import "fmt"

Multi line import

import (
    "fmt"
        "time"
)

time package

The time.Time type represents time.

func main(){
    now := time.Now()
    fmt.Printf("current time is :%v\n",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)
}

time stamp

The timestamp is the total number of milliseconds from January 1, 1970 (08:00:00 GMT) to the current time. It is also known as a Unix timestamp.

func timestampDemo() {
    now := time.Now()            //Get current time
    timestamp1 := now.Unix()     //time stamp
    timestamp2 := now.UnixNano() //Nanosecond time stamp
    fmt.Printf("current timestamp1:%v\n", timestamp1)
    fmt.Printf("current timestamp2:%v\n", timestamp2)
}

Use the time.Unix() function to format the timestamp as time.

func timestampDemo2(timestamp int64) {
    timeObj := time.Unix(timestamp, 0) //Convert timestamps to time format
    fmt.Println(timeObj)
    year := timeObj.Year()     //year
    month := timeObj.Month()   //month
    day := timeObj.Day()       //day
    hour := timeObj.Hour()     //hour
    minute := timeObj.Minute() //Minute
    second := timeObj.Second() //second
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second)
}

timer

Use time.tick to set the timer.

func tickDemo(){
    ticker := time.Tick(time.Second)
    for i:=range ticker{
        fmt.Println(i)
    }

}

time interval

The Duration type represents the elapsed time between two time points, in nanoseconds. The maximum time period that can be expressed is about 290 years. Define the time interval constant as follows:

const (
    Nanosecond Duration =1
        Microsecond               =1000*Nanosecond
        Millisecond                  =1000*Microsecond
        Second                        =1000*Millisecond
        Minute                         =60*Second
        Hour                            =60*Minute
)

For example: time.Duration represents 1 nanosecond, time.Second represents 1 second.

Time plus time interval

We may meet the requirement of time + time interval in the daily coding process. The time object of Go language provides the following Add methods:

func (t Time) Add(d Duration) Time

For example, find the time after an hour:

func main(){
    now := time.Now()
    later := now.Add(time.Hour)
    fmt.Println(later)
}

Two times minus each other

Find the difference between two times:

func (t Time) Sub(u time) Duration

Posted by sandrine2411 on Sun, 03 Nov 2019 16:27:47 -0800