Table of Contents
Getting the Current Time
Calculating Time Differences with Duration
Working with Time Zones
Scheduling and Sleep
Home Backend Development Golang How do I use the time package to work with time and durations in Go?

How do I use the time package to work with time and durations in Go?

Jun 23, 2025 pm 11:21 PM
go time processing

Go's time package provides functions for processing time and duration, including obtaining the current time, formatting date, calculating time difference, processing time zone, scheduling and sleeping operations. To get the current time, use time.Now() to get the Time structure, and you can extract specific time information through Year(), Month(), Day() and other methods; use Format("2006-01-02 15:04:05") can format time into a string; when calculating the time difference, use Sub() or Since() to obtain the Duration object, and then convert it into the corresponding unit through Seconds(), Minutes(), and Hours(); use Add() method to add or subtract time; use UTC() to obtain the coordinated world time when processing time zones, or use LoadLocation ("time zone name") to load the specified time zone and call In(); parsing the time string requires Parse() and providing a time layout matching the input; use Sleep() to implement delays, and periodic tasks can use NewTicker() to create tickers and listen to their channels in goroutines, and stop tickers when completed to free resources.

How do I use the time package to work with time and durations in Go?

Working with time and durations in Go is straightforward thanks to the built-in time package. Whether you need to get the current time, format dates, calculate durations, or schedule events, this package has most of what you need.


Getting the Current Time

The first thing you usually want to do is get the current moment. In Go, that's as simple as calling time.Now() :

 now := time.Now()
fmt.Println(now)

This returns a Time struct that contains all the details—year, month, day, hour, minute, second, and even nanoseconds. You can extract individual components like this:

  • now.Year()
  • now.Month()
  • now.Day()
  • now.Hour() , etc.

If you're logging events or displaying timestamps, it's often useful to format the time in a readable way using a reference time:
Mon Jan 2 15:04:05 MST 2006 . That might look odd, but just remember—it's the specific moment Go uses for formatting:

 fmt.Println(now.Format("2006-01-02 15:04:05"))

Calculating Time Differences with Duration

When you want to compare two moments or measure how much time has passed, use Sub() :

 start := time.Now()
// some operation
elapsed := time.Since(start) // or time.Now().Sub(start)

The result is a Duration , which represents the elapsed time between two points. It's measured in nanoseconds internally, but you can convert it into more usable units:

  • elapsed.Seconds()
  • elapsed.Minutes()
  • elapsed.Hours()

You can also add or subtract durations from a time:

 later := now.Add(2 * time.Hour)

This is handy when scheduling events or simulating future/past times.


Working with Time Zones

By default, time.Now() gives you the local time, but sometimes you need to work with UTC or another time zone:

 utcNow := time.Now().UTC()

To parse or display time in a specific zone, you'll need to load the location first:

 loc, _ := time.LoadLocation("America/New_York")
nyTime := time.Now().In(loc)

Parsing time strings also require specifying the layout and optionally the location:

 t, _ := time.Parse("2006-01-02 15:04", "2024-03-10 14:30")

Make sure your input string matches the format exactly, or parsing will fail.


Scheduling and Sleep

For delays or time-based operations, time.Sleep() and time.Tick() are useful:

 time.Sleep(2 * time.Second) // pause execution

If you want something to happen periodically (like a heartbeat), use a ticker:

 ticker := time.NewTicker(1 * time.Second)
go func() {
    for t := range ticker.C {
        fmt.Println("Tick at", t)
    }
}()

Don't forget to stop the ticker when you're done to avoid resource leaks.


That's the basic toolkit for handling time and durations in Go. The time package covers most common scenarios without needing external libraries. Some things—like date math beyond days or complex timezone rules—might require extra care, but for the majority of applications, this should be enough to get started.

The above is the detailed content of How do I use the time package to work with time and durations in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

The folder or file has been opened in another program The folder or file has been opened in another program Sep 20, 2025 am 08:24 AM

When the file is occupied, first check and close the relevant programs and try to restart the computer; if it is invalid, use task manager, resource monitor or ProcessExplorer to locate the occupied process, and forcefully terminate it by ending the task or taskkill command; for prevention, you need to develop good operating habits, avoid previewing or directly operating on mobile/network drives, and keep software updated.

BTC is 'digesting future market trends ahead of time': 5 most noteworthy Bitcoin points this week BTC is 'digesting future market trends ahead of time': 5 most noteworthy Bitcoin points this week Sep 20, 2025 pm 01:39 PM

Table of Contents As traditional financial markets recover, Bitcoin volatility has risen significantly. The Fed's interest rate cut expectation has become the focus of the market. The peak of Bitcoin bull market may be "only a few weeks left". Binance has seen a large-scale buy signal. ETFs continue to absorb newly mined BTC. Bitcoin (BTC) investors are closely following market trends as crypto assets enter the Fed's key interest rate decision window. At the beginning of this week, bulls need to break through the important resistance level of $117,000 to continue their uptrend. Global attention is focused on Wednesday's Federal Reserve meeting, and it is generally predicted that it will usher in the first rate cut in 2025. A past accurate BTC price model shows that all-time highs may be born in the next few weeks. Binance Order Book reveals signs of large buying influx over the weekend. Last week, the amount of BTC purchased by institutions through ETFs reached miners

Where to find folders Where to find folders Sep 20, 2025 am 07:57 AM

The most direct way is to recall the storage location, usually in folders such as desktop, documents, downloads, etc.; if it cannot be found, you can use the system search function. File "missing" is mostly due to problems such as unattention of the saving path, name memory deviation, file hiding or cloud synchronization. Efficient management suggestions: Classify by project, time, and type, make good use of quick access, clean and archive regularly, and standardize naming. Windows search and search through File Explorer and taskbar, while macOS relies on finder and Spotlight, which is smarter and more efficient. Mastering tools and developing good habits is the key.

What is Somnia (SOMI) currency? Introduction to recent price trends and future outlook What is Somnia (SOMI) currency? Introduction to recent price trends and future outlook Sep 17, 2025 am 06:18 AM

Directory What is Somnia (SOMI)? Price performance and market trends: Short-term volatility and long-term potential Technical advantages: Why can Somnia challenge the traditional Layer1? Future Outlook: 2025-2030 Price Forecast Conclusion: Somnia's Opportunities and SEO Content Opportunities Somnia (SOMI) is a high-performance Layer1 blockchain native token launched in September 2025. It has recently attracted much attention from the market due to its price fluctuations and technological innovation. As of September 12, 2025, Gate exchange data showed that SOMI price was temporarily at $1.28, although it had a pullback from the historical high of $1.90, it was still better than the main one.

What is USDH currency? How does it work? Full analysis of Hyperliquid new stablecoin What is USDH currency? How does it work? Full analysis of Hyperliquid new stablecoin Sep 17, 2025 pm 04:39 PM

Source: Polymarket On Friday, September 5, 2025, Hyperliquid, which currently occupies an absolute leading position in decentralized derivatives exchanges, announced that it is seeking to issue a "Hyperliquid-first, consistent with Hyperliquid's interests and compliant US dollar stablecoin" and invites the team to submit proposals. The launch of the new stablecoin USDH of Hyperliquid has triggered fierce competition among market makers. Major players such as Paxos, Sky and FraxFinance have all joined the competition to issue USDH, but the lesser-known NativeMarkets is at the forefront. As adoption increases, liquidity supply

What is Ethereum (ETH) currency? ETH price forecast 2025-2030 What is Ethereum (ETH) currency? ETH price forecast 2025-2030 Sep 17, 2025 pm 04:42 PM

Directory What is Ethereum? Why is its prediction relevant? Highlights of ETH price related to key upgrades: Key factors affecting ETH price forecasting Network technology progress Supply and demand dynamics Institutional demand Macro background ETH forecast for 2025: What are you looking forward to? What happened in 2026 ETH forecast: Medium-term trend 2030 Ethereum forecast: Long-term outlook How do we analyze ETH price forecast Comparative conclusions of Ethereum with other major cryptocurrencies: The future of Ethereum and its price forecast How to trade Ethereum? Frequently Asked Questions What Factors Impact

Good news: China's largest currency holding company plans to increase its position in Bitcoin through additional issuance of US$500 million in stocks Good news: China's largest currency holding company plans to increase its position in Bitcoin through additional issuance of US$500 million in stocks Sep 20, 2025 pm 01:03 PM

Key information of the catalog: NextTechnology has become the 15th largest enterprise-level Bitcoin holder in the world. Strategy has firmly ranked first in the global corporate currency holding list with 636,505 BTC. NextTechnologyHolding - China's listed company with the most Bitcoin holdings, plans to raise up to US$500 million through the public issuance of common shares to further increase its holdings in BTC and support other companies' strategic layout. Key information: NextTechnology plans to raise $500 million for financing

Understand RoboFi in one article and understand the new star projects on the Web3 robot ecosystem track Understand RoboFi in one article and understand the new star projects on the Web3 robot ecosystem track Sep 16, 2025 pm 11:51 PM

Directory 1.@openmind_agi2.@peaq3.@GEODNET_4.@psdnai5.@PrismaXai6.@NRNAgents7.@AukiNetwork8.@RoboStack_io9.@frodobots9.1.@BitRobotNetwork9.2.@ET_Fugi9.3.@samismoving9.4.@robotsdotfun9.5.@UFBotsSummary 1.@openmind_agi Keywords: Operating System, Decentralized Collaborative Layer

See all articles