Golang is an efficient and concise programming language that is widely used in various fields. In development, we often need to convert time, such as converting strings to time, converting time to strings, etc., and the different time formats will also cause certain problems. Therefore, this article will introduce the time conversion operation in Golang and explain its specific usage through examples.
1. Convert string to time
In Golang, we can use the Parse function in the time package to convert a string into time. The specific definition of the Parse function is as follows:
func Parse(layout, value string) (Time, error)
Among them, layout represents the time format of the string to be converted, and value represents the character to be converted. string. These two parameters can use the predefined constants in the time package. The specific constants and their meanings are as follows:
Time constant | Meaning |
---|---|
ANSIC | "Mon Jan _2 15:04:05 2006" |
UnixDate | "Mon Jan _2 15:04:05 MST 2006" |
RFC3339 | "2006-01-02T15:04:05Z07:00" |
For example, the sample code to convert the string "2022/04/12 15:20:00" into time is as follows:
timeStr := "2022/04/12 15:20:00" layout := "2006/01/02 15:04:05" t, err := time.Parse(layout, timeStr) if err != nil { fmt.Println("转化失败:", err) } else { fmt.Println("转化成功:", t) }
Among them, timeStr is the string to be converted, layout is the time format of a string ("2006/01/02 15:04:05" represents the year, month, day, hour, minute, and second), t is the time object obtained after conversion, and err is the error message during the conversion process. Run the above code and the output result is as follows:
转化成功: 2022-04-12 15:20:00 +0000 UTC
2. Convert time to string
Similarly, in Golang, we can use the Format function to convert time into a string. The specific definition of this function is as follows:
func (t Time) Format(layout string) string
Among them, t is the time object to be converted, and layout represents the formatted time string. Its usage is also similar to the Parse function introduced above.
For example, the sample code to convert time into a string in the format of "2022/04/12 15:20:00" is as follows:
t := time.Now() layout := "2006/01/02 15:04:05" timeStr := t.Format(layout) fmt.Println("转化后时间字符串:", timeStr)
Among them, t is the current time and layout is the conversion The format of the subsequent time ("2006/01/02 15:04:05" represents the year, month, day, hour, minute, and second), and timeStr is the converted time string. Run the above code and the output result is as follows:
转化后时间字符串: 2022/04/12 15:20:00
3. Time zone conversion
In Golang, the time zone representation of time can be obtained using the Location function in the time package. Its definition is as follows:
func LoadLocation(name string) (*Location, error)
Among them, name represents the time zone name (such as "Asia/Shanghai").
For example, when converting local time to UTC time, you can use the UTC function in the time package. The sample code is as follows:
t := time.Now() utc := t.UTC() fmt.Println("本地时间:", t) fmt.Println("UTC时间:", utc)
Among them, t is the local time and utc is the converted UTC time. Run the above code and the output result is as follows:
本地时间: 2022-10-07 15:24:56.200122 +0800 CST m=+0.000498761 UTC时间: 2022-10-07 07:24:56.200122 +0000 UTC
4. Time addition and subtraction
In Golang, time addition and subtraction can be performed using the Add function and Sub function. Its specific definition is as follows:
func (t Time) Add(d Duration) Time
func (t Time) Sub(u Time) Duration
Among them, the Add function adds time t The previous Duration object d returns a new time object; the Sub function subtracts another time object u from time t and returns a Duration object.
For example, the sample code for adding 10 minutes to the existing time is as follows:
t := time.Now() d := 10 * time.Minute newTime := t.Add(d) fmt.Println("原时间:", t) fmt.Println("加10分钟后的时间:", newTime)
Among them, t is the existing time, d is the time interval to be added (10 minutes), newTime is the new time obtained after adding. Run the above code and the output result is as follows:
原时间: 2022-10-07 15:35:26.924559 +0800 CST m=+0.000213898 加10分钟后的时间: 2022-10-07 15:45:26.924559 +0800 CST
5. How to optimize the time conversion efficiency
In actual development, we may have a large number of time conversion needs, and use Golang’s own time Converting the package will greatly reduce the efficiency of the program. At this time, we can use third-party libraries for optimization.
Currently, the more popular time conversion libraries include:
- The time conversion component in the Gorm library
- Rob Pike’s open source Time library
- Bjoernu's open source TimeUtils library
These third-party libraries can greatly improve the efficiency of time conversion, and also solve the problems caused by different time layouts on different systems.
Summary
This article introduces the operation of time conversion in Golang, including converting strings into time, converting time into strings, time zone conversion, and time addition and subtraction. At the same time, some common time conversion libraries are also provided to optimize time conversion efficiency. I hope this article can provide some help to Golang developers in time conversion.
The above is the detailed content of golang time conversion. For more information, please follow other related articles on the PHP Chinese website!

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

SublimeText3 English version
Recommended: Win version, supports code prompts!

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools