Time dan Date

Go menyediakan package time untuk mengelola waktu dan tanggal. Package ini menyediakan berbagai fungsi untuk parsing, formatting, dan manipulasi waktu.

Contoh Masalah

Bagaimana cara:

  1. Mengelola waktu dan tanggal
  2. Format dan parse waktu
  3. Operasi aritmatika waktu
  4. Timezone handling

Penyelesaian

package main

import (
    "fmt"
    "time"
)

// 1. Time formatting helper
func formatTime(t time.Time, layout string) string {
    return t.Format(layout)
}

// 2. Age calculator
func calculateAge(birthdate time.Time) int {
    now := time.Now()
    age := now.Year() - birthdate.Year()
    
    // Adjust age if birthday hasn't occurred this year
    if now.YearDay() < birthdate.YearDay() {
        age--
    }
    
    return age
}

// 3. Duration formatter
func formatDuration(d time.Duration) string {
    days := int(d.Hours() / 24)
    hours := int(d.Hours()) % 24
    minutes := int(d.Minutes()) % 60
    seconds := int(d.Seconds()) % 60

    return fmt.Sprintf("%dd %dh %dm %ds", days, hours, minutes, seconds)
}

// 4. Business hours checker
func isBusinessHour(t time.Time) bool {
    // Convert to local time
    t = t.Local()
    
    // Check if weekend
    if t.Weekday() == time.Saturday || t.Weekday() == time.Sunday {
        return false
    }
    
    // Check if between 9 AM and 5 PM
    hour := t.Hour()
    return hour >= 9 && hour < 17
}

func main() {
    // Contoh 1: Basic time operations
    fmt.Println("Basic Time Operations:")
    now := time.Now()
    fmt.Printf("Current time: %v\n", now)
    fmt.Printf("Unix timestamp: %v\n", now.Unix())
    fmt.Printf("Nanoseconds: %v\n", now.Nanosecond())
    
    // Contoh 2: Time formatting
    fmt.Printf("\nTime Formatting:\n")
    layouts := []string{
        time.RFC3339,
        time.RFC822,
        "2006-01-02",
        "02/01/2006 15:04:05",
        "Monday, 02-Jan-06",
    }
    
    for _, layout := range layouts {
        fmt.Printf("Format %s: %s\n", layout, formatTime(now, layout))
    }

    // Contoh 3: Time parsing
    fmt.Printf("\nTime Parsing:\n")
    dateStr := "2006-01-02 15:04:05"
    t, err := time.Parse("2006-01-02 15:04:05", dateStr)
    if err != nil {
        fmt.Printf("Error parsing time: %v\n", err)
    } else {
        fmt.Printf("Parsed time: %v\n", t)
    }

    // Contoh 4: Time arithmetic
    fmt.Printf("\nTime Arithmetic:\n")
    tomorrow := now.Add(24 * time.Hour)
    yesterday := now.Add(-24 * time.Hour)
    nextWeek := now.AddDate(0, 0, 7)
    lastMonth := now.AddDate(0, -1, 0)
    
    fmt.Printf("Tomorrow: %v\n", tomorrow)
    fmt.Printf("Yesterday: %v\n", yesterday)
    fmt.Printf("Next week: %v\n", nextWeek)
    fmt.Printf("Last month: %v\n", lastMonth)

    // Contoh 5: Duration calculations
    fmt.Printf("\nDuration Calculations:\n")
    start := time.Now()
    time.Sleep(2 * time.Second)
    duration := time.Since(start)
    
    fmt.Printf("Operation took: %v\n", duration)
    fmt.Printf("Formatted duration: %s\n", formatDuration(duration))

    // Contoh 6: Timezone handling
    fmt.Printf("\nTimezone Handling:\n")
    locations := []string{
        "America/New_York",
        "Europe/London",
        "Asia/Tokyo",
        "Australia/Sydney",
    }
    
    for _, loc := range locations {
        location, err := time.LoadLocation(loc)
        if err != nil {
            fmt.Printf("Error loading location %s: %v\n", loc, err)
            continue
        }
        
        timeInLoc := now.In(location)
        fmt.Printf("Time in %s: %s\n", loc, timeInLoc.Format(time.RFC3339))
    }

    // Contoh 7: Age calculation
    fmt.Printf("\nAge Calculation:\n")
    birthdate := time.Date(1990, time.January, 1, 0, 0, 0, 0, time.UTC)
    age := calculateAge(birthdate)
    fmt.Printf("Age: %d years\n", age)

    // Contoh 8: Business hours
    fmt.Printf("\nBusiness Hours Check:\n")
    checkTimes := []time.Time{
        time.Date(2024, 1, 21, 10, 0, 0, 0, time.Local), // Sunday
        time.Date(2024, 1, 22, 14, 0, 0, 0, time.Local), // Monday
        time.Date(2024, 1, 22, 8, 0, 0, 0, time.Local),  // Monday early
        time.Date(2024, 1, 22, 18, 0, 0, 0, time.Local), // Monday late
    }
    
    for _, t := range checkTimes {
        fmt.Printf("%s is business hour: %v\n",
            t.Format("Monday 15:04"), isBusinessHour(t))
    }

    // Contoh 9: Time comparison
    fmt.Printf("\nTime Comparison:\n")
    time1 := time.Now()
    time2 := time1.Add(time.Hour)
    
    fmt.Printf("time1 before time2: %v\n", time1.Before(time2))
    fmt.Printf("time1 after time2: %v\n", time1.After(time2))
    fmt.Printf("time1 equal to time2: %v\n", time1.Equal(time2))

    // Contoh 10: Timer and Ticker
    fmt.Printf("\nTimer and Ticker:\n")
    
    // Timer example
    timer := time.NewTimer(2 * time.Second)
    go func() {
        <-timer.C
        fmt.Println("Timer expired")
    }()

    // Ticker example
    ticker := time.NewTicker(1 * time.Second)
    go func() {
        for i := 0; i < 3; i++ {
            <-ticker.C
            fmt.Println("Tick")
        }
        ticker.Stop()
    }()

    // Wait for goroutines to finish
    time.Sleep(3 * time.Second)
}

Penjelasan Kode

  1. Basic Time

    • Current time
    • Unix timestamp
    • Time components
  2. Time Operations

    • Formatting
    • Parsing
    • Arithmetic
  3. Advanced Features

    • Timezone
    • Duration
    • Timer/Ticker

Output

Basic Time Operations:
Current time: 2024-01-21 11:57:22.123456789 +0700 WIB
Unix timestamp: 1705812642
Nanoseconds: 123456789

Time Formatting:
Format 2006-01-02T15:04:05Z07:00: 2024-01-21T11:57:22+07:00
Format 02 Jan 06 15:04 MST: 21 Jan 24 11:57 WIB
Format 2006-01-02: 2024-01-21
Format 02/01/2006 15:04:05: 21/01/2024 11:57:22
Format Monday, 02-Jan-06: Sunday, 21-Jan-24

Time Parsing:
Parsed time: 2006-01-02 15:04:05 +0000 UTC

Time Arithmetic:
Tomorrow: 2024-01-22 11:57:22.123456789 +0700 WIB
Yesterday: 2024-01-20 11:57:22.123456789 +0700 WIB
Next week: 2024-01-28 11:57:22.123456789 +0700 WIB
Last month: 2023-12-21 11:57:22.123456789 +0700 WIB

Duration Calculations:
Operation took: 2.001234567s
Formatted duration: 0d 0h 0m 2s

Timezone Handling:
Time in America/New_York: 2024-01-20T23:57:22-05:00
Time in Europe/London: 2024-01-21T04:57:22+00:00
Time in Asia/Tokyo: 2024-01-21T13:57:22+09:00
Time in Australia/Sydney: 2024-01-21T15:57:22+11:00

Age Calculation:
Age: 34 years

Business Hours Check:
Sunday 10:00 is business hour: false
Monday 14:00 is business hour: true
Monday 08:00 is business hour: false
Monday 18:00 is business hour: false

Time Comparison:
time1 before time2: true
time1 after time2: false
time1 equal to time2: false

Timer and Ticker:
Tick
Tick
Timer expired
Tick

Tips

  • Gunakan time.Time untuk waktu
  • Perhatikan timezone
  • Format waktu dengan konstanta layout
  • Handle parsing error
  • Gunakan duration untuk interval