DEV Community

threadspeed
threadspeed

Posted on

Go time package examples

#go

You can use the module "time" to deal with time and date in Golang.

The Package time provides functionality for measuring and displaying time: calendrical calculations always assume a Gregorian calendar, with no leap seconds.

To load the time module you can do this:

import (                                                                                                             
        "fmt"                                                                                                        
        "time"                                                                                                       
)   

The example below shows the day given a date and formats two dates.

package main                                                                                                         


import (                                                                                                             
        "fmt"                                                                                                        
        "time"                                                                                                       
)                                                                                                                    

func days(year int, month time.Month) int {                                                                          
        return time.Date(year, month+1, 0, 0, 0, 0, 0, time.UTC).Day()                                               
}                                                                                                                    

func main() {                                                                                                        
        fmt.Println(days(2019, 2)) // 28                                                                             
        fmt.Printf("%v", time.Date(2019, 3, 0, 0, 0, 0, 0, time.UTC)) // 2019-02-28 00:00:00 +0000 UTC               
        fmt.Println()                                                                                                
        fmt.Printf("%v", time.Now().Format("2006-01-02 15:04:05"))                                                   
}          

To get the elapsed time (while your program ran), try this code:

package main

import (
        "fmt"
        "time"
)

func main() {
        startTime := time.Now()
        time.Sleep(1 * time.Second)
        elapsed := time.Since(startTime)
        fmt.Printf("elapsed %v", elapsed) // elapsed 1.0005049s
}

Related:

Top comments (0)