Golang Date & Time | Find Output Programs | Set 1

This section contains the Golang Date & Time find output programs (set 1) with their output and explanations.
Submitted by Nidhi, on October 22, 2021

Program 1:

package main

import "fmt"
import "time"

func main() {
	var currentDateAndTime string
	currentDateAndTime = time.Now()
	fmt.Println("Current date and time\n", currentDateAndTime)
}

Output:

./prog.go:8:21: cannot use time.Now() (type time.Time) as type string in assignment

Explanation:

The above program will generate a syntax error. Because time.Now() returns an object of Time class. Here we need to convert it into a string.

The correct code is given below,

package main

import "fmt"
import "time"

func main() {
	var currentDateAndTime string
	currentDateAndTime = time.Now().String()
	fmt.Println("Current date and time\n", currentDateAndTime)
}

/*
Output:
Current date and time
 2009-11-10 23:00:00 +0000 UTC m=+0.000000001
*/

Program 2:

package main

import "fmt"
import "time"

func main() {
	dateTime := time.Now()
	fmt.Println(dateTime.Format("01-02-2006"))
	fmt.Println(dateTime.Format("01-02-2007"))
}

Output:

10-08-2021
10-08-8007

Explanation:

The above program will print dates on the console screen.

fmt.Println(dateTime.Format("01-02-2006"))

The above statement will print the correct date, In Golang we used "01-02-2006" to print the date in the correct format.


Program 3:

package main

import "fmt"
import "time"

func main() {
	YYYY, MM, DD := time.Now().Date()
	fmt.Println("Date : ", DD)
	fmt.Println("Month: ", MM)
	fmt.Println("Year : ", YYYY)
}

Output:

Date :  10
Month:  November
Year :  2009

Explanation:

In the above program, we are getting the day, month, and year using time.Now.Date() method and printed.


Program 4:

package main

import "fmt"
import "time"

func main() {
	X := time.Now()

	A := X.Day()
	B := X.Month()
	C := X.Year()

	fmt.Printf("\nResult: %d", int(A)+int(B)+int(C))
}

Output:

Result: 2039

Explanation:

In the above program, we got the day, month, and year using time.Now() method and printed the sum of day, month, and year values. Here we are considering the date 08-10-2021.


Program 5:

package main

import "fmt"
import "time"

func main() {
	date := time.Date(2020, 2, 5, 0, 0, 0, 0, time.UTC)
	res := date.AddDate(1, 3, 7)

	fmt.Println("Result : ", res)
}

Output:

Result :  2021-05-12 00:00:00 +0000 UTC

Explanation:

In the above program, we created a date object with a specified date. Then we added the specified date using the AddDate() method and printed the result.

Golang Find Output Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.