Learning Center
Go

Working with Date and Time in Go Using the time Package

28 Jan 2025
Hostman Team
Hostman Team

Go (Golang), like many other programming languages, has a built-in time package that provides special types and methods for working with dates and times.

You can find comprehensive information about the time package in the official documentation. This guide will cover the basic aspects of working with time in Go. 

All the examples shown were run on a cloud server provided by Hostman, using the Ubuntu 22.04 operating system and Go version 1.21.3.

It is assumed that you are already familiar with the basics of Go and know how to run scripts using the appropriate interpreter command:

go run script.go

Parsing, Formatting, and Creating Dates
Copy link

Before getting started with time manipulation, it's important to understand a key feature of time formatting in Go.

In most programming languages, date and time formats are specified using special symbols, which are replaced by values representing day, month, year, hour, minute, and second.

However, Go approaches this differently. Instead of special symbols, it uses default date and time values represented by an increasing sequence of numbers:

01-02-03-04-05-06

This sequence of numbers represents:

  1. 1st month of the year (January)
  2. 2nd day of the month
  3. 3rd hour in 12-hour format (p.m.)
  4. 4th minute in 12-hour format (p.m.)
  5. 5th second in 12-hour format (p.m.)
  6. 6th year of the 21st century

Thus, this results in the following time format:

January 2nd, 3:04:05 PM, 2006

Or in another form: 02.01.2006 03:04:05 PM

It is important to remember that this value is nothing more than a regular increasing sequence of numbers without any special significance.

Therefore, this date and time act as a predefined layout for working with any explicitly specified date and time values.

For example, here’s an abstract (not Go-specific) pseudocode example:

currentTime = time.now()

console.write("Current date: ", currentTime.format("%D.%M.%Y"))  
console.write("Current time: ", currentTime.format("%H:%M"))  
console.write("Current date and time: ", currentTime.format("%D.%M.%Y %H:%M"))

In our pseudo-console, this would produce the following pseudo-output:

Current date: 26.11.2024  
Current time: 14:05  
Current date and time: 26.11.2024 14:05

This is how date and time formatting works in most programming languages.

In Go, however, the pseudocode would look like this:

currentTime = time.now()

console.write("Current date: ", currentTime.format("02.01.2006"))  
console.write("Current time: ", currentTime.format("03:04"))  
console.write("Current date and time: ", currentTime.format("02.01.2006 03:04"))

The console output would be similar:

Current date: 26.11.2024  
Current time: 14:05  
Current date and time: 26.11.2024 14:05

Here, the standard template values for date and time are automatically replaced with the actual date and time values.

Additionally, template values have certain variations. For instance, you can specify the month 01 as Jan.

Thanks to this approach, Go allows templates to be defined in a more intuitive and human-readable way.

Parsing
Copy link

Working with time in Go starts by explicitly specifying it. This can be done using the time parsing function:

package main

import (
    "fmt"      // package for console I/O
    "time"     // package for working with time
    "reflect"  // package for determining variable types
)

func main() {
    timeLayout := "2006-01-02"        // time layout template
    timeValue := "2024-11-16"         // time value to be parsed

    timeVariable, err := time.Parse(timeLayout, timeValue)  // parsing time value using the template
    if err != nil { 
        panic(err)  // handling possible parsing errors
    }

    fmt.Println(timeVariable)                 // output the parsed time variable to the console
    fmt.Println(reflect.TypeOf(timeVariable)) // output the type of the time variable
}

When you run the script, the terminal will display the following output:

2024-11-16 00:00:00 +0000 UTC  
time.Time

Note that after parsing, a variable of type time.Time is created. This variable stores the parsed time value in its internal format.

In the example shown, the time layout and value could be replaced with another equivalent format.

func main() {
timeLayout := "2006-Jan-02"
timeValue:= "2024-Nov-16"
...

The final result would remain the same.

During parsing, an additional parameter can be specified to set the time zone, also known as the time offset or time zone:

package main

import (
	"fmt"
	"time"
)

func main() {
	// Local

	timeLocation, err := time.LoadLocation("Local")
	if err != nil { panic(err) }

	timeVariable, err := time.ParseInLocation("2006-01-02 15:04", "2024-11-16 07:45", timeLocation)
	if err != nil { panic(err) }

	fmt.Println("Local: ", timeVariable)

	// Asia/Bangkok

	timeLocation, err = time.LoadLocation("Asia/Bangkok")
	if err != nil { panic(err) }

	timeVariable, err = time.ParseInLocation("2006-01-02 15:04", "2024-11-16 07:45", timeLocation)
	if err != nil { panic(err) }
 
	fmt.Println("Asia/Bangkok: ", timeVariable)

	// Europe/Nicosia

	timeLocation, err = time.LoadLocation("Europe/Nicosia")
	if err != nil { panic(err) }

	timeVariable, err = time.ParseInLocation("2006-01-02 15:04", "2024-11-16 07:45", timeLocation)
	if err != nil { panic(err) }
 
	fmt.Println("Europe/Nicosia: ", timeVariable)
}

The console output of this script will be as follows:

Local:  2024-11-16 07:45:00 +0000 UTC
Asia/Bangkok:  2024-11-16 07:45:00 +0700 +07
Europe/Nicosia:  2024-11-16 07:45:00 +0300 EET

Instead of explicitly creating a time zone variable, you can use a predefined constant:

package main

import (
	"fmt"
	"time"
)

func main() {
	// time.LoadLocation("Local")

	timeLocation, err := time.LoadLocation("Local")
	if err != nil { panic(err) }

	timeVariable, err := time.ParseInLocation("2006-01-02 15:04", "2024-11-16 07:45", timeLocation)
	if err != nil { panic(err) }

	fmt.Println(timeVariable)

	// time.Local

	timeVariable, err = time.ParseInLocation("2006-01-02 15:04", "2024-11-16 07:45", time.Local)
	if err != nil { panic(err) }

	fmt.Println(timeVariable)
}

In this case, the complete date and time values in both variants will be identical.

2024-11-16 07:45:00 +0000 UTC
2024-11-16 07:45:00 +0000 UTC

You can find a complete list of available time zones in the so-called Time Zone Database (tz database).

Time zone identifiers are specified using two region names separated by a slash. For example:

  • Europe/Nicosia
  • Asia/Dubai
  • US/Alaska

Formatting
Copy link

We can format an already created time variable to represent its value as a specific text string.

Thus, a variable of type time.Time has built-in methods for converting date and time into a string type.

package main

import (
	"fmt"
	"time"
)

func main() {
	timeLayout := "2006-01-02 15:04:05"
	timeValue := "2024-11-15 12:45:20"
 
	timeVariable, err := time.Parse(timeLayout, timeValue)
	if err != nil { panic(err) }

	fmt.Print("\r", "DATE", "\r\n")

	fmt.Println(timeVariable.Format("2006-01-02"))
	fmt.Println(timeVariable.Format("01/02/06"))
	fmt.Println(timeVariable.Format("01/02/2006"))
	fmt.Println(timeVariable.Format("20060102"))
	fmt.Println(timeVariable.Format("010206"))
	fmt.Println(timeVariable.Format("January 02, 2006"))
	fmt.Println(timeVariable.Format("02 January 2006"))
	fmt.Println(timeVariable.Format("02-Jan-2006"))
	fmt.Println(timeVariable.Format("Jan-02-06"))
	fmt.Println(timeVariable.Format("Jan-02-2006"))
	fmt.Println(timeVariable.Format("06"))
	fmt.Println(timeVariable.Format("Mon"))
	fmt.Println(timeVariable.Format("Monday"))
	fmt.Println(timeVariable.Format("Jan-06"))

	fmt.Print("\r", "TIME", "\r\n")

	fmt.Println(timeVariable.Format("15:04"))
	fmt.Println(timeVariable.Format("15:04:05"))
	fmt.Println(timeVariable.Format("3:04 PM"))
	fmt.Println(timeVariable.Format("03:04:05 PM"))

	fmt.Print("\r", "DATE and TIME", "\r\n")

	fmt.Println(timeVariable.Format("2006-01-02T15:04:05"))
	fmt.Println(timeVariable.Format("2 Jan 2006 15:04:05"))
	fmt.Println(timeVariable.Format("2 Jan 2006 15:04"))
	fmt.Println(timeVariable.Format("Mon, 2 Jan 2006 15:04:05 MST"))

	fmt.Print("\r", "PREDEFINED FORMATS", "\r\n")

	fmt.Println(timeVariable.Format(time.RFC1123)) // predefined format
	fmt.Println(timeVariable.Format(time.Kitchen)) // predefined format
	fmt.Println(timeVariable.Format(time.Stamp)) // predefined format
	fmt.Println(timeVariable.Format(time.DateOnly)) // predefined format
}

Running this script will output various possible date and time formats in the terminal:

DATE

2024-11-15
11/15/24
11/15/2024
20241115
111524
November 15, 2024
15 November 2024
15-Nov-2024
Nov-15-24
Nov-15-2024
24
Fri
Friday
Nov-24

TIME

12:45
12:45:20
12:45 PM
12:45:20 PM

DATE and TIME

2024-11-15T12:45:20
15 Nov 2024 12:45:20
15 Nov 2024 12:45
Fri, 15 Nov 2024 12:45:20 UTC

PREDEFINED FORMATS

Fri, 15 Nov 2024 12:45:20 UTC
12:45PM
Nov 15 12:45:20
2024-11-15

Pay attention to the last few formats, which are predefined as constant values. These constants provide commonly used date and time formats in a convenient, ready-to-use form.

You can find a complete list of these constants in the official documentation.

time.Layout

01/02 03:04:05PM '06 -0700

time.ANSIC

Mon Jan _2 15:04:05 2006

time.UnixDate

Mon Jan _2 15:04:05 MST 2006

time.RubyDate

Mon Jan 02 15:04:05 -0700 2006

time.RFC822

02 Jan 06 15:04 MST

time.RFC822Z

02 Jan 06 15:04 -0700

time.RFC850

Monday, 02-Jan-06 15:04:05 MST

time.RFC1123

Mon, 02 Jan 2006 15:04:05 MST

time.RFC1123Z

Mon, 02 Jan 2006 15:04:05 -0700

time.RFC3339

2006-01-02T15:04:05Z07:00

time.RFC3339Nano

2006-01-02T15:04:05.999999999Z07:00

time.Kitchen

3:04PM

time.Stamp

Jan _2 15:04:05

time.StampMilli

Jan _2 15:04:05.000

time.StampMicro

Jan _2 15:04:05.000000

time.StampNano

Jan _2 15:04:05.000000000

time.DateTime

2006-01-02 15:04:05

time.DateOnly

2006-01-02

time.TimeOnly

15:04:05

Another common method to format date and time in Go is by converting it to Unix time. 

package main

import (
	"fmt"
	"time"
	"reflect"
)
func main() {
    timeVariable := time.Unix(350, 50) // set Unix time to 350 seconds and 50 nanoseconds from January 1, 1970, 00:00:00

    fmt.Println("Time:", timeVariable) // display time in UTC format

    timeUnix := timeVariable.Unix()
    timeUnixNano := timeVariable.UnixNano()

    fmt.Println("Time (UNIX, seconds):", timeUnix) // display time in Unix format (seconds)
    fmt.Println("Time (UNIX, nanoseconds):", timeUnixNano) // display time in Unix format (nanoseconds)
    fmt.Println("Time (type):", reflect.TypeOf(timeUnix)) // display the variable type for Unix time
}

After running this script, the following output will appear in the terminal:

Time:  1970-01-01 00:05:50.00000005 +0000 UTC  
Time (UNIX, seconds):  350  
Time (UNIX, nanoseconds):  350000000050  
Time (type):  int64

Note that the variable created to store the Unix time value is of type int64, not time.Time.

Thus, by using formatting, you can perform conversions between string-based time and Unix time and vice versa:

package main

import (
	"fmt"
	"time"
)

func main() {
	timeString, _ := time.Parse("2006-01-02 15:04:05", "2024-11-15 12:45:20")
	fmt.Println(timeString.Unix())

	timeUnix := time.Unix(12345, 50)
	fmt.Println(timeUnix.Format("2006-01-02 15:04:05"))
}

The console output of this script will display the results of conversions to and from Unix time:

1731674720
1970-01-01 03:25:45

Creation
Copy link

In Go, there is a more straightforward way to create a time.Time variable by explicitly setting the date and time parameters:

package main

import (
    "fmt"
    "time"
)

func main() {
    timeLocation, _ := time.LoadLocation("Europe/Vienna")

    // year, month, day, hour, minute, second, nanosecond, time zone
    timeVariable := time.Date(2024, 11, 20, 12, 30, 45, 50, timeLocation)

    fmt.Print(timeVariable)
}

After running this script, the following output will appear in the terminal:

2024-11-20 12:30:45.00000005 +0100 CET

Current Date and Time
Copy link

In addition to manually setting arbitrary dates and times, you can set the current date and time:

package main

import (
    "fmt"
    "time"
    "reflect"
)

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

    fmt.Println(timeNow)
    fmt.Println(timeNow.Format(time.DateTime))
    fmt.Println(timeNow.Unix())
    fmt.Println(reflect.TypeOf(timeNow))
}

After running this script, the following output will appear in the terminal:

2024-11-27 17:08:18.195495127 +0000 UTC m=+0.000035621
2024-11-27 17:08:18
1732727298
time.Time

As you can see, the time.Now() function creates the familiar time.Time variable, whose values can be formatted arbitrarily.

Extracting Parameters
Copy link

The time.Time variable consists of several parameters that together form the date and time:

  • Year
  • Month
  • Day
  • Weekday
  • Hour
  • Minute
  • Second
  • Nanosecond
  • Time zone

Go provides a set of methods to extract and modify each of these parameters.

Most often, you will need to retrieve specific parameters from an already created time variable:

package main

import (
    "fmt"
    "time"
    "reflect"
)

func main() {
    timeLayout := "2006-01-02 15:04:05"
    timeValue := "2024-11-15 12:45:20"

    timeVariable, _ := time.Parse(timeLayout, timeValue)

    fmt.Println("Year:", timeVariable.Year())
    fmt.Println("Month:", timeVariable.Month())
    fmt.Println("Day:", timeVariable.Day())
    fmt.Println("Weekday:", timeVariable.Weekday())
    fmt.Println("Hour:", timeVariable.Hour())
    fmt.Println("Minute:", timeVariable.Minute())
    fmt.Println("Second:", timeVariable.Second())
    fmt.Println("Nanosecond:", timeVariable.Nanosecond())
    fmt.Println("Time zone:", timeVariable.Location())

    fmt.Println("")

    fmt.Println("Year (type):", reflect.TypeOf(timeVariable.Year()))
    fmt.Println("Month (type):", reflect.TypeOf(timeVariable.Month()))
    fmt.Println("Day (type):", reflect.TypeOf(timeVariable.Day()))
    fmt.Println("Weekday (type):", reflect.TypeOf(timeVariable.Weekday()))
    fmt.Println("Hour (type):", reflect.TypeOf(timeVariable.Hour()))
    fmt.Println("Minute (type):", reflect.TypeOf(timeVariable.Minute()))
    fmt.Println("Second (type):", reflect.TypeOf(timeVariable.Second()))
    fmt.Println("Nanosecond (type):", reflect.TypeOf(timeVariable.Nanosecond()))
    fmt.Println("Time zone (type):", reflect.TypeOf(timeVariable.Location()))
}

The console output of this script will be:

Year: 2024
Month: November
Day: 15
Weekday: Friday
Hour: 12
Minute: 45
Second: 20
Nanosecond: 0
Time zone: UTC

Year (type): int
Month (type): time.Month
Day (type): int
Weekday (type): time.Weekday
Hour (type): int
Minute (type): int
Second (type): int
Nanosecond (type): int
Time zone (type): *time.Location

Thus, you can individually retrieve specific information about the date and time without needing to format the output before displaying it in the console.

Note the types of the retrieved variables — all of them have the int type except for a few:

  • Month (time.Month)
  • Weekday (time.Weekday)
  • Time zone (*time.Location)

The last one (time zone) is a pointer.

Modification, Addition, and Subtraction
Copy link

Modification
Copy link

You cannot change the parameters of date and time directly in an already created time.Time variable. However, you can recreate the variable with updated values, thus changing the existing date and time:

package main

import (
	"fmt"
	"time"
)

func main() {
	timeVariable := time.Now()
	fmt.Println(timeVariable)

	// year, month, day, hour, minute, second, nanosecond, time zone
	timeChanged := time.Date(timeVariable.Year(), timeVariable.Month(), timeVariable.Day(), timeVariable.Hour() + 14, timeVariable.Minute(), timeVariable.Second(), timeVariable.Nanosecond(), timeVariable.Location())
	fmt.Println(timeChanged)
}

When running this script, the following output will appear:

2024-11-28 14:35:05.287957345 +0000 UTC m=+0.000039131
2024-11-29 04:35:05.287957345 +0000 UTC

In this example, 14 hours were added to the current time. This way, you can selectively update the time values in an existing time.Time variable.

Change by Time Zone
Copy link

Sometimes, it is necessary to determine what the specified date and time will be in a different time zone. For this, Go provides a special method:

package main

import (
	"fmt"
	"time"
)

func main() {
	locationFirst, _ := time.LoadLocation("Europe/Nicosia")
	timeFirst := time.Date(2000, 1, 1, 0, 0, 0, 0, locationFirst)

	fmt.Println("Time (Europe/Nicosia)", timeFirst)

	locationSecond, _ := time.LoadLocation("America/Chicago")
	timeSecond := timeFirst.In(locationSecond) // changing the time zone and converting the date and time based on it

	fmt.Println("Time (America/Chicago)", timeSecond)
}

The result of running the script will produce the following console output:

Time (Europe/Nicosia) 2000-01-01 00:00:00 +0200 EET 
Time (America/Chicago) 1999-12-31 16:00:00 -0600 CST

Thus, we obtain new date and time values, updated according to the newly specified time zone.

Addition and Subtraction
Copy link

Go does not have separate methods for date and time addition. Instead, you can add time intervals to an already created time.Time variable:

package main

import (
	"fmt"
	"time"
)

func main() {
	// current time
	timeVariable := time.Now()
	fmt.Println(timeVariable)

	// adding 5 days (24 hours * 5 days = 120 hours)
	timeChanged := timeVariable.Add(120 * time.Hour)
	fmt.Println(timeChanged)

	// subtracting 65 days (24 hours * 65 days = 1560 hours)
	timeChanged = timeVariable.Add(-1560 * time.Hour)
	fmt.Println(timeChanged)
}

Running this script will give the following output:

2024-12-05 08:42:01.927334604 +0000 UTC m=+0.000035141
2024-12-10 08:42:01.927334604 +0000 UTC m=+432000.000035141
2024-10-01 08:42:01.927334604 +0000 UTC m=-5615999.999964859

Note that when subtracting a sufficient number of days from the time.Time variable, the month is also modified.

Also, the time.Hour variable actually has a special type, time.Duration:

package main

import (
	"fmt"
	"time"
	"reflect"
)

func main() {
	fmt.Println(reflect.TypeOf(time.Hour))
	fmt.Println(reflect.TypeOf(120* time.Hour))
}

The output after running the script will be:

time.Duration
time.Duration

However, modifying the date and time by adding or subtracting a large number of hours is not very clear. In some cases, it is better to use more advanced methods for changing the time:

package main

import (
	"fmt"
	"time"
)

func main() {
	timeVariable := time.Now()
	fmt.Println(timeVariable)

	// year, month, day
	timeChanged := timeVariable.AddDate(3, 2, 1)
	fmt.Println(timeChanged)

	// day
	timeChanged = timeChanged.AddDate(0, 0, 15)
	fmt.Println(timeChanged)

	// year, month
	timeChanged = timeChanged.AddDate(5, 1, 0)
	fmt.Println(timeChanged)

	// -year, -day
	timeChanged = timeChanged.AddDate(-2, 0, -10)
	fmt.Println(timeChanged)
}

After running this script, the output will look like this:

2024-11-28 17:51:45.769245873 +0000 UTC m=+0.000024921
2028-01-29 17:51:45.769245873 +0000 UTC
2028-02-13 17:51:45.769245873 +0000 UTC
2033-03-13 17:51:45.769245873 +0000 UTC
2031-03-03 17:51:45.769245873 +0000 UTC

Subtraction
Copy link

Unlike addition, Go has specialized methods for subtracting one time.Time variable from another.

package main

import (
	"fmt"
	"time"
	"reflect"
)

func main() {
	timeFirst := time.Date(2024, 6, 14, 0, 0, 0, 0, time.Local)
	timeSecond := time.Date(2010, 3, 26, 0, 0, 0, 0, time.Local)

	timeDeltaSub := timeFirst.Sub(timeSecond) // timeFirst - timeSecond
	timeDeltaSince := time.Since(timeFirst) // time.Now() - timeFirst
	timeDeltaUntil := time.Until(timeFirst) // timeFirst - time.Now()

	fmt.Println("timeFirst - timeSecond =", timeDeltaSub)
	fmt.Println("time.Now() - timeFirst =", timeDeltaSince)
	fmt.Println("timeFirst - time.Now() =", timeDeltaUntil)

	fmt.Println("")

	fmt.Println(reflect.TypeOf(timeDeltaSub))
	fmt.Println(reflect.TypeOf(timeDeltaSince))
	fmt.Println(reflect.TypeOf(timeDeltaUntil))
}

Console output:

timeFirst - timeSecond = 124656h0m0s
time.Now() - timeFirst = 4029h37m55.577746026s
timeFirst - time.Now() = -4029h37m55.577746176s

time.Duration
time.Duration
time.Duration

As you can see, the result of the subtraction is the familiar time.Duration type variable.

In fact, the main function for finding the difference is time.Time.Sub(), and the other two are just its derivatives:

package main

import (
	"fmt"
	"time"
)

func main() {
	timeVariable := time.Date(2024, 6, 14, 0, 0, 0, 0, time.Local)

	fmt.Println(time.Now().Sub(timeVariable))
	fmt.Println(time.Since(timeVariable))

	fmt.Println("")

	fmt.Println(timeVariable.Sub(time.Now()))
	fmt.Println(time.Until(timeVariable))
}

Console output:

4046h10m53.144212707s
4046h10m53.144254987s

-4046h10m53.144261117s
-4046h10m53.144267597s

You can see that the results of these described functions are identical.

  • time.Time.Since() = time.Now().Sub(timeVariable)
  • time.Time.Until() = timeVariable.Sub(time.Now())

Time Durations
Copy link

Individual time intervals (durations) in the time package are represented as a special variable of type time.Duration. Unlike time.Time, they store not full date and time but time intervals.

With durations, you can perform some basic operations that modify their time parameters.

Parsing Durations
Copy link

A duration is explicitly defined using a string containing time parameters:

package main

import (
	"fmt"
	"time"
)

func main() {
	// hours, minutes, seconds
	durationHMS, _ := time.ParseDuration("4h30m20s")
	fmt.Println("Duration (HMS):", durationHMS)

	// minutes, seconds
	durationMS, _ := time.ParseDuration("6m15s")
	fmt.Println("Duration (MS):", durationMS)

	// hours, minutes
	durationHM, _ := time.ParseDuration("2h45m")
	fmt.Println("Duration (HM):", durationHM)

	// hours, seconds
	durationHS, _ := time.ParseDuration("2h10s")
	fmt.Println("Duration (HS):", durationHS)

	// hours, minutes, seconds, milliseconds, microseconds, nanoseconds
	durationFULL, _ := time.ParseDuration("6h50m40s30ms4µs3ns")
	fmt.Println("Full Duration:", durationFULL)
}

Output of the script:

Duration (HMS): 4h30m20s  
Duration (MS): 6m15s  
Duration (HM): 2h45m0s  
Duration (HS): 2h0m10s  
Full Duration: 6h50m40.030004003s

Note the last duration, which contains all possible time parameters in decreasing order of magnitude—hours, minutes, seconds, milliseconds, microseconds, and nanoseconds.

During parsing, each parameter is specified using the following keywords:

  • Hours — h
  • Minutes — m
  • Seconds — s
  • Milliseconds — ms
  • Microseconds — µs
  • Nanoseconds — ns

Moreover, the order of specifying duration parameters does not affect it:

package main

import (
	"fmt"
	"time"
)

func main() {
	duration, _ := time.ParseDuration("7ms20s4h30m")
	fmt.Println("Duration:", duration)
}

Terminal output:

Duration: 4h30m20.007s

Formatting Durations
Copy link

In Go, we can represent the same duration in different units of measurement:

package main

import (
	"fmt"
	"time"
	"reflect"
)

func main() {
	duration, _ := time.ParseDuration("4h30m20s")

	fmt.Println("Duration:", duration)

	fmt.Println("")

	fmt.Println("In hours:", duration.Hours())
	fmt.Println("In minutes:", duration.Minutes())
	fmt.Println("In seconds:", duration.Seconds())
	fmt.Println("In milliseconds:", duration.Milliseconds())
	fmt.Println("In microseconds:", duration.Microseconds())
	fmt.Println("In nanoseconds:", duration.Nanoseconds())

	fmt.Println("")

	fmt.Println(reflect.TypeOf(duration.Hours()))
	fmt.Println(reflect.TypeOf(duration.Minutes()))
	fmt.Println(reflect.TypeOf(duration.Seconds()))
	fmt.Println(reflect.TypeOf(duration.Milliseconds()))
	fmt.Println(reflect.TypeOf(duration.Microseconds()))
	fmt.Println(reflect.TypeOf(duration.Nanoseconds()))
}

Output of the script:

Duration: 4h30m20s

In hours: 4.5055555555555555  
In minutes: 270.3333333333333  
In seconds: 16220  
In milliseconds: 16220000  
In microseconds: 16220000000  
In nanoseconds: 16220000000000  

float64  
float64  
float64  
int64  
int64  
int64

As you can see, the parameters for hours, minutes, and seconds are of type float64, while the rest are of type int.

Conclusion
Copy link

This guide covered the basic functions for working with dates and times in the Go programming language, all of which are part of the built-in time package.

Thus, Go allows you to:

  • Format dates and times
  • Convert dates and times
  • Set time zones
  • Extract specific date and time parameters
  • Set specific date and time parameters
  • Add and subtract dates and times
  • Execute code based on specific time settings

For more detailed information on working with the time package, refer to the official Go documentation.

In addition, you can deploy Go applications (such as Beego and Gin) on our app platform.