Q:

Golang Date & Time | Find Output Programs | Set 1

0

This section contains the Golang Date & Time find output programs (set 1) with their output and explanations.

Program 1:

package main

import "fmt"
import "time"

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

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"))
}

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)
}

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))
}

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)
}

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer Program 1:

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
*/

 

Answer Program 2:

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.


Answer Program 3:

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.


 

Answer Program 4:

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.


 

Answer Program 5:

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now