Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - DATE & TIME


Date and Time is one of the important topic in any programming language. In Go we can import the module named 'time' to work with Date and Time.


Let us start with the below example.


Example :



package main
import "fmt"
import "time" 
    
func main() { 
     
    x := time.Now()
    fmt.Println(x)
}


Output :



 2020-12-20 15:11:04.111497 +0530 IST m=+0.000101845

Now, if we dissect the output,


java_Collections

So, with the below statement,


x := time.Now()

We get the date and time in the variable, 'x' that has Year, Month, Day, Hour, Minute, Second and Microsecond.


So, you got the date in clubbed format. Now, what if you want everything separately.


Well! Go provides that way as well.


Example :



package main
import "fmt"
import "time" 
    
func main() { 
     
    x := time.Now()
            
    year := x.Year()
    month := x.Month()
    day := x.Day()
    hour := x.Hour()
    minute := x.Minute()
    second := x.Second()
    nanoSecond := x.Nanosecond()
            
    fmt.Println("The full format is ", x)
    fmt.Println("The year is ",year)
    fmt.Println("The month is ",month)
    fmt.Println("The day is ",day)
    fmt.Println("The hour is ",hour)
    fmt.Println("The minute is ",minute)
    fmt.Println("The second is ",second)
    fmt.Println("The nanoSecond is ",nanoSecond)
}


Output :



 The full format is 2021-02-04 15:18:27.975556 +0530 IST m=+0.000083603
 The year is 2021
 The month is February
 The day is 4
 The hour is 15
 The minute is 18
 The second is 27
 The nanoSecond is 975556000

Now, if you look at the above output, we have separated the clubbed formatted date.


To display the year, you need to invoke 'x.Year()'.


year := x.Year()

Similar, logic applies for Month, Day, Hour, Minute, Second and Microsecond.