Golang convert from ISO 8601 to milliseconds
package main
import (
"fmt"
"time"
)
func main() {
iso8601String := "2023-12-05T10:30:45Z"
// Parse ISO 8601 string to time.Time object
parsedTime, err := time.Parse(time.RFC3339, iso8601String)
if err != nil {
fmt.Println("Error parsing time:", err)
return
}
// Convert time.Time to milliseconds since Unix epoch
milliseconds := parsedTime.UnixNano() / int64(time.Millisecond)
fmt.Println("Milliseconds since Unix epoch:", milliseconds)
}
Explanation:
1. Import the required packages: fmt
for formatting and printing, and time
for handling time-related operations.
2. Define an example ISO 8601 string representing a date and time in UTC format.
3. Use time.Parse
to convert the ISO 8601 string into a time.Time
object (parsedTime
). The time.RFC3339
format is used for parsing ISO 8601 strings.
4. Check if there's an error while parsing the time. If an error occurs, it prints the error message and stops further execution.
5. Calculate the number of milliseconds since the Unix epoch (January 1, 1970 UTC) using parsedTime.UnixNano()
to get the time in nanoseconds and then dividing it by int64(time.Millisecond)
to convert it to milliseconds.
6. Print the number of milliseconds since the Unix epoch.