Open In App

time.Date() 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 Date() function in Go language is used to find Date the Time which is equivalent to yyyy-mm-dd hh:mm:ss + nsec nanoseconds in the proper time zone in the stated location. 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 Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time

Here, “loc” is pointed to the location.

Return Value: It returns a time that is proper in one of the two associated zones in the conversion, but it won’t guarantee that which one is returned. And it returns panics if the given “loc” is nil.

Note: Here, the value of the month, day hour, min, sec and nsec can be more than the normal ranges but they will be automatically normalized during the conversion. For example, if the date is April 34 then it is converted to May 1.

Example 1:




// Golang program to illustrate the usage of
// time.Date() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Calling Date() method 
    // with all its parameters
    tm := time.Date(2020, time.April,
        11, 21, 34, 01, 0, time.UTC)
  
    // Using Local() for location and printing
    // the stated time and date in UTC
    fmt.Printf("%s", tm.Local())
}


Output:

2020-04-11 21:34:01 +0000 UTC

Example 2:




// Golang program to illustrate the usage of
// time.Date() function
  
// Including main package
package main
  
// Importing fmt and time
import "fmt"
import "time"
  
// Calling main
func main() {
  
    // Calling Date() method 
    // with all its parameters
    tm := time.Date(2020, time.April, 
          34, 25, 72, 01, 0, time.UTC)
  
    // Using Local() for location and printing
    // the stated time and date in UTC
    fmt.Printf("%s", tm.Local())
}


Output:

2020-05-05 02:12:01 +0000 UTC

Here, the range of the values of day, hours, and minutes is outside the normal range but they are normalized during the conversion.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads