Sling Academy
Home/Golang/How to convert time to UNIX timestamp in Go

How to convert time to UNIX timestamp in Go

Last updated: November 26, 2024

Converting time to a UNIX timestamp is a common task in many programming applications. It transforms a specific date and time to the number of seconds that have elapsed since January 1, 1970 (the UNIX epoch). In this article, we'll explore how to perform this conversion using the Go programming language.

Understanding the UNIX Timestamp

The UNIX timestamp is an integer value that counts the number of seconds since the UNIX epoch. This makes it a convenient way to store and compare times, as well as simplifying the process of working with different time zones and locales.

Go's time Package

Go, being a modern programming language, provides strong support for date and time manipulation through its time package. We'll utilize this package to convert a given time to a UNIX timestamp.

Step-by-step Guide

1. Import the Required Package

Start by importing Go’s time package in your Go file. This package contains all the necessary functionalities for handling time in Go.

package main

import (
    "fmt"
    "time"
)

2. Create a Time Instance

Next, create an instance of time.Time that represents the date and time you wish to convert. For example, let's construct a time.Time object representing October 1, 2023, at 12:00 PM UTC.

func main() {
    // Layout to parse string into time.Time object
    const layout = "2006-01-02 15:04:05"
    // String representation of the date and time
    dateStr := "2023-10-01 12:00:00"

    // Parsing the string into a time.Time object
    t, err := time.Parse(layout, dateStr)
    if err != nil {
        fmt.Println(err)
        return
    }

3. Convert Time to UNIX Timestamp

Once you have a time.Time instance, call its Unix() method to obtain the UNIX timestamp.

    // Conversion to UNIX timestamp
    unixTimestamp := t.Unix()

    // Output the result
    fmt.Printf("UNIX Timestamp: %d\n", unixTimestamp)
}

Complete Example

Below is the complete code demonstrating the conversion of a specific time to UNIX timestamp.

package main

import (
    "fmt"
    "time"
)

func main() {
    const layout = "2006-01-02 15:04:05"
    dateStr := "2023-10-01 12:00:00"

    t, err := time.Parse(layout, dateStr)
    if err != nil {
        fmt.Println(err)
        return
    }

    unixTimestamp := t.Unix()
    fmt.Printf("UNIX Timestamp: %d\n", unixTimestamp)
}

Conclusion

You've learned how to convert a date and time to a UNIX timestamp in Go using the time package. This process involves parsing a date string into a time.Time object and then converting it into a UNIX timestamp with the Unix() method. This method is efficient and suits most scenarios where time conversion is required in application development.

Next Article: How to convert UNIX timestamp to time in Go

Previous Article: How to convert local time to UTC time and vice versa in Go

Series: Working with Date & Time in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant