Chapter 10: About Time

Introduksyon

Time. Dili na mobalik ang panahon, pero at least makontrol nato sa code. Ang Go time package kay naay everything para sa dates, times, durations, ug time zones. Anhi nga chapter, magkat-on ta maghimo, mag-compare, mag-format, ug mag-manipulate ug time — unlike sa imong schedule na wala juy klaro.

Making Time

Paghimo ug time values — gamit ug time.Now() para sa current time, or time.Date() para specific dates. Mura rag "unsa oras?" vs "July 4, 2024 — naay okasyon?":

now := time.Now()
fmt.Println(now)  // 2024-01-15 10:30:00 +0800 PST

specific := time.Date(2024, time.July, 4, 12, 0, 0, 0, time.UTC)
fmt.Println(specific)  // 2024-07-04 12:00:00 +0000 UTC

Exercise 10.1: Creating a Function to Return a timestamp

Goal: Magsulat ug function na mobalik ug current timestamp as formatted string.

package main

import (
    "fmt"
    "time"
)

func timestamp() string {
    return time.Now().Format("2006-01-02 15:04:05")
}

func main() {
    fmt.Println("Current time:", timestamp())
}

Comparing Time

Gamit ug Before, After, Equal, ug Sub para sa comparisons — parehas rag mag-check ka kung ang birthday sa imong uyab before or after sa imo (importante ni ha):

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

fmt.Println(later.After(now))   // true
fmt.Println(now.Before(later))  // true
fmt.Println(now.Equal(now))     // true

diff := later.Sub(now)
fmt.Println(diff)               // 2h0m0s

Duration Calculation

Ang durations kay nagrepresentar ug elapsed time sa nanoseconds. Pero ayaw kabalaka — naay constants para mas klaro. Mura rag "gahuwat kog 2h30m15s" imbes "gahuwat kog 9015000000000 nanoseconds":

d := 2*time.Hour + 30*time.Minute + 15*time.Second
fmt.Println(d)             // 2h30m15s
fmt.Println(d.Minutes())   // 150.25
fmt.Println(d.Seconds())   // 9015
fmt.Println(d.Milliseconds())  // 9015000

Managing Time

Mag-add or subtract ug time gamit Add ug AddDate — parehas rag mag-add ka ug days sa imong deadline kay wala pa nahuman ang code:

now := time.Now()
tomorrow := now.Add(24 * time.Hour)
nextMonth := now.AddDate(0, 1, 0)    // year, month, day
lastYear := now.AddDate(-1, 0, 0)

fmt.Println(tomorrow)
fmt.Println(nextMonth)

Exercise 10.2: Duration of Execution

Goal: Sukaton kung pila ka dugay ang function mo-execute.

package main

import (
    "fmt"
    "time"
)

func slowFunction() {
    time.Sleep(500 * time.Millisecond)
}

func main() {
    start := time.Now()
    slowFunction()
    elapsed := time.Since(start)

    fmt.Printf("Execution time: %s\n", elapsed)
    fmt.Printf("Milliseconds: %d\n", elapsed.Milliseconds())
}

Formatting Time

Ang Go kay nagamit ug reference time para sa formatting. Dili nang YYYY-MM-DD — Go unique ra jud: Mon Jan 2 15:04:05 MST 2006. Ang mnemonic: 1-2-3-4-5-6-7. Seryoso. Wala ko nag-imbento:

now := time.Now()
fmt.Println(now.Format("2006-01-02"))              // 2024-01-15
fmt.Println(now.Format("Monday, Jan 2, 2006"))     // Monday, Jan 15, 2024
fmt.Println(now.Format("3:04 PM"))                 // 10:30 AM
fmt.Println(now.Format(time.RFC3339))              // 2024-01-15T10:30:00+08:00

Exercise 10.03: What Is the Time in Your Zone?

Goal: I-print ang current time sa tulo ka lain-laing time zones.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    locNY, _ := time.LoadLocation("America/New_York")
    locLondon, _ := time.LoadLocation("Europe/London")
    locTokyo, _ := time.LoadLocation("Asia/Tokyo")

    fmt.Println("Local:", now.Format("2006-01-02 15:04:05 MST"))
    fmt.Println("NY:   ", now.In(locNY).Format("2006-01-02 15:04:05 MST"))
    fmt.Println("London:", now.In(locLondon).Format("2006-01-02 15:04:05 MST"))
    fmt.Println("Tokyo: ", now.In(locTokyo).Format("2006-01-02 15:04:05 MST"))
}

Activity 10.01: Formatting a Date According to User Requirements

Goal: Kuha ug date string "2024-03-15" ug i-format as "March 15, 2024 (Friday)".

package main

import (
    "fmt"
    "time"
)

func main() {
    input := "2024-03-15"
    t, _ := time.Parse("2006-01-02", input)
    fmt.Println(t.Format("January 2, 2006 (Monday)"))
}

Activity 10.02: Enforcing a Specific Format of Date and Time

Goal: I-validate kung ang date string kay match sa expected format "YYYY/MM/DD".

package main

import (
    "fmt"
    "time"
)

func main() {
    inputs := []string{"2024/03/15", "2024-03-15", "15-03-2024"}
    layout := "2006/01/02"

    for _, input := range inputs {
        _, err := time.Parse(layout, input)
        if err != nil {
            fmt.Printf("%q: invalid format\n", input)
        } else {
            fmt.Printf("%q: valid\n", input)
        }
    }
}

Activity 10.03: Measuring Elapsed Time

Goal: Sukaton ug i-print ang total time sa tulo ka sequential operations.

package main

import (
    "fmt"
    "time"
)

func main() {
    start := time.Now()

    time.Sleep(100 * time.Millisecond)
    time.Sleep(200 * time.Millisecond)
    time.Sleep(150 * time.Millisecond)

    elapsed := time.Since(start)
    fmt.Printf("Total elapsed: %s\n", elapsed)
}

Activity 10.04: Calculating the Future Date and Time

Goal: Kwentaha ang date 90 days gikan karon ug i-print.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    future := now.AddDate(0, 0, 90)

    fmt.Println("Today:     ", now.Format("2006-01-02"))
    fmt.Println("90 days later:", future.Format("2006-01-02"))
    fmt.Println("Day of week:", future.Weekday())
}

Activity 10.05: Printing the Local Time in Different Time Zones

Goal: I-convert ang current time sa UTC, EST, ug IST (India) ug i-display ang tulo.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()
    locIST := time.FixedZone("IST", 5*60*60+30*60)

    fmt.Println("UTC:", now.UTC().Format("15:04:05"))
    fmt.Println("EST:", now.In(time.FixedZone("EST", -5*60*60)).Format("15:04:05"))
    fmt.Println("IST:", now.In(locIST).Format("15:04:05"))
}

Summary