Golang program to format time in AM-PM format


In Go language article, we will write programs to format time in AM-PM format using now and format package, as well as using now and format function with minutes and seconds.

The current time can be obtained using Now function from the time package whereas we can format the time using Format function as we are going to use in this article. In this article we will use “now and format function” to get the formatted time in AM-PM format.

Syntax

funcNow() Time

The Now() function is defined in time package. This function generates the current local time. To use this function, we have to first import the time package in our program.

time.Format()

This function is present in the time package. It takes a layout input string that depicts how the output string will be formatted.

Algorithm

  • Step 1 − Import the required packages in the program

  • Step 2 − Create a main function

  • Step 3 − Obtain the formatted time in AM-PM format using built-in functions

  • Step 4 − Print the formatted time on the console using fmt package’s Println function

Example 1

Following golang program to format time in AM-PM format using Now and format function. In this Example, we will use Now function from the time package to get the current time then we will use format function to get the formatted time, where 6 represents the 12-hour format and pm refers to the meridian indicator of afternoon time.

package main

import (
   "fmt"
   "time"
)

func main() {
   Time := time.Now()
   fmt.Println("Current time in AM/PM format:", Time.Format("6:00 PM"))
}

Output

Current time in AM/PM format: 6:00 PM

Example 2

Following Golang program to format time in AM-PM format using Now and format function with minutes and seconds. In this illustration, format will be used with 6 representing the 12-hour format whereas the 6:06 represent the minutes and seconds and am represents the meridian indicator of morning time.

package main

import (
   "fmt"
   "time"
)

func main() {
   Time := time.Now()
   am_pm_time := Time.Format("6:06:06 AM")
   fmt.Println("Current time in AM/PM format:", am_pm_time)
}

Output

Current time in AM/PM format: 6:09:09 AM

Conclusion

We have successfully executed the program of formatting time in AM-PM format. In both of the Examples we used Now and format to format the time but in in the second Example we used seconds along with morning time whereas in the first Example we used afternoon time.

Updated on: 03-May-2023

657 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements