Open In App

time.Unix() Function in Golang with Examples

Last Updated : 21 Apr, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, time packages supplies functionality for determining as well as viewing time. The Unix() function in Go language is used to yield the local time which is related to the stated Unix time from January 1, 1970, in UTC. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.

Syntax:

func Unix(sec int64, nsec int64) Time

Here, “sec” is seconds which is of type int64 and “nsec” is nanoseconds which is also of type int64.

Note: It is reasonable to permit “nsec” outside the range [0, 999999999]. However, not every “sec” values have a equivalent time value and one analogous value is 1<<63-1, which is the largest int64 value.

Return value: It returns the local time which is equivalent to the stated Unix time from January 1, 1970 in UTC.

Example 1:




// Golang program to illustrate the usage of
// time.Unix() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Calling Unix method with 275 seconds
    // and zero nanoseconds and also
    // printing output
    fmt.Println(time.Unix(275, 0).UTC())
  
    // Calling Unix method with 0 seconds and
    // 566 nanoseconds and also printing
    // output
    fmt.Println(time.Unix(0, 566).UTC())
  
    // Calling Unix method with 456 seconds and
    // -67 nanoseconds and also printing
    // output
    fmt.Println(time.Unix(456, -67).UTC())
}


Output:

1970-01-01 00:04:35 +0000 UTC
1970-01-01 00:00:00.000000566 +0000 UTC
1970-01-01 00:07:35.999999933 +0000 UTC

Example 2:




// Golang program to illustrate the usage of
// time.Unix() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Calling Unix method with 2e1 seconds
    // and zero nanoseconds and also
    // printing output
    fmt.Println(time.Unix(2e1, 0).UTC())
  
    // Calling Unix method with 0 seconds and
    // 1e13 nanoseconds and also printing
    // output
    fmt.Println(time.Unix(0, 1e13).UTC())
  
    // Calling Unix method with 1e1 seconds and
    // -1e15 nanoseconds and also printing
    // output
    fmt.Println(time.Unix(1e1, -1e15).UTC())
}


Output:

1970-01-01 00:00:20 +0000 UTC
1970-01-01 02:46:40 +0000 UTC
1969-12-20 10:13:30 +0000 UTC

Here, the parameters of the Unix() method stated in the above code have values that contain a constant “e” which is converted in usual range while conversion.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads