Date Range by Week Number in Go
Given the week number obtained using the provided Week function, this article explores how to determine the corresponding date range starting on Sunday.
Foreword: ISO Week and Custom Handling
It's important to note that the standard ISO Week starts on Monday. To adapt to this convention, the following approach handles weeks starting on either Monday or Sunday.
Week Range Determination
To determine the date range of a week, we:
- Start from the middle of the year (July 1st).
- Align to the first day of the week (Monday by default).
- Get the week number of this time value.
- Corrigate by adding or subtracting days based on the week difference.
Implementation:
func WeekStart(year, week int) time.Time { t := time.Date(year, 7, 1, 0, 0, 0, 0, time.UTC) if wd := t.Weekday(); wd == time.Sunday { t = t.AddDate(0, 0, -6) } else { t = t.AddDate(0, 0, -int(wd)+1) } _, w := t.ISOWeek() t = t.AddDate(0, 0, (week-w)*7) return t }
Example Usage:
fmt.Println(WeekStart(2018, 1)) // Output: 2018-01-01 00:00:00 +0000 UTC fmt.Println(WeekStart(2018, 2)) // Output: 2018-01-08 00:00:00 +0000 UTC
Handling Out-of-Range Weeks:
This implementation handles out-of-range weeks gracefully, interpreting them as weeks of the previous or next year.
Determining End of Week:
To obtain the last day of the week, simply add 6 days to the week's first day:
func WeekRange(year, week int) (start, end time.Time) { start = WeekStart(year, week) end = start.AddDate(0, 0, 6) return }
The above is the detailed content of How to Calculate the Date Range for a Given Week Number in Go?. For more information, please follow other related articles on the PHP Chinese website!

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.

The article discusses using Go's "strings" package for string manipulation, detailing common functions and best practices to enhance efficiency and handle Unicode effectively.

The article details using Go's "crypto" package for cryptographic operations, discussing key generation, management, and best practices for secure implementation.Character count: 159

The article details the use of Go's "time" package for handling dates, times, and time zones, including getting current time, creating specific times, parsing strings, and measuring elapsed time.

Article discusses using Go's "reflect" package for variable inspection and modification, highlighting methods and performance considerations.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
