Skip to content

time: Truncate in NZ timezone changes the day when removing all time fields #9949

@jennerm

Description

@jennerm

Hi,

I am relatively new to Go and I am trying out the different built-in libraries to see how they work. I was trying out time.Truncate and came across an unexpected result. I am in New Zealand and was truncating all the time fields from a local datetime value. Rather than just truncate the time fields, the new value has also gone to the previous day. I suppose it did the truncation on the underlying value in UTC.

The sample program below demonstrates the issue and produces the following output:

dateOnly(2015-02-21 11:30:00 +1300 NZDT) was 2015-02-20 13:00:00 +1300 NZDT, but wanted 2015-02-21 00:00:00 +1300 NZDT

package main

import (
    "fmt"
    "log"
    "time"
)

const layout = "2006 Jan 02 15:04:05 MST"

func main() {
    dateTime, dateWithTimeTruncated := parseTestDates("2015 Feb 21 11:30:00.0 NZDT", "2015 Feb 21 00:00:00.0 NZDT")
    if !dateOnly(dateTime).Equal(dateWithTimeTruncated) {
        fmt.Printf("dateOnly(%v) was %v, but wanted %v", dateTime, dateOnly(dateTime), dateWithTimeTruncated)
    }
}

// Truncate the time component and leave only the date fields
func dateOnly(t time.Time) time.Time {
    return t.Truncate(time.Hour * 24)
}

func parseTestDates(dateWithTime string, dateWithoutTime string) (dateTime time.Time, dateWithTimeTruncated time.Time) {
    dateTime, err := time.Parse(layout, dateWithTime)
    if err != nil {
        log.Fatal(err)
    }
    dateWithTimeTruncated, err = time.Parse(layout, dateWithoutTime)
    if err != nil {
        log.Fatal(err)
    }
    return dateTime, dateWithTimeTruncated
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions