Time Parsing Fundamentals
Parsing Time from Strings
func parseTimeExamples() {
// Standard time format parsing
standardTime, err := time.Parse(time.RFC3339, "2023-06-15T14:30:00Z")
if err != nil {
fmt.Println("Parsing error:", err)
}
// Custom format parsing
customTime, err := time.Parse("2006-01-02", "2023-12-25")
if err != nil {
fmt.Println("Custom parsing error:", err)
}
}
graph TD
A[Reference Time] --> B[2006-01-02]
A --> C[15:04:05]
A --> D[MST]
Format Specifier |
Meaning |
Example |
2006 |
4-digit year |
2023 |
01 |
2-digit month |
12 |
02 |
2-digit day |
25 |
15 |
24-hour time |
14 |
04 |
Minutes |
30 |
05 |
Seconds |
45 |
func advancedFormatting() {
now := time.Now()
// Multiple formatting styles
formats := []string{
time.RFC3339,
"2006-01-02",
"Monday, January 2, 2006",
"15:04:05 MST",
}
for _, format := range formats {
formatted := now.Format(format)
fmt.Println(formatted)
}
}
func complexParsing() {
// Handling multiple input formats
timeStrings := []string{
"2023-06-15 14:30:00",
"15/06/2023",
"June 15, 2023",
}
layouts := []string{
"2006-01-02 15:04:05",
"02/01/2006",
"January 2, 2006",
}
for i, timeStr := range timeStrings {
parsedTime, err := time.Parse(layouts[i], timeStr)
if err != nil {
fmt.Printf("Error parsing %s: %v\n", timeStr, err)
continue
}
fmt.Printf("Parsed: %v\n", parsedTime)
}
}
Time Zone Parsing
func timeZoneParsing() {
// Parsing with explicit time zone
location, _ := time.LoadLocation("America/New_York")
zoneTime, err := time.ParseInLocation(
"2006-01-02 15:04:05",
"2023-06-15 14:30:00",
location,
)
if err != nil {
fmt.Println("Zone parsing error:", err)
}
}
LabEx Practical Tip
In LabEx cloud environments, consistently use UTC or specify time zones explicitly to avoid unexpected parsing results.
Best Practices
- Use
time.Parse()
for string to time conversion
- Always handle potential parsing errors
- Use the reference time
2006-01-02 15:04:05
for custom formats
- Be consistent with time zone handling
- Validate parsed times before further processing