spf13 / spf13/cast

Why ToTimeE() use UTC as the default instead of Local?

Open
#225 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Go
Stars
4k
Forks
337
Avg merge
15m
Merged PRs (30d)
1

Description

I used cast.ToTime () to convert '2006-01-02 15:04:05' format time string, and then compared with time.Now(), there is a problem. I would like to ask why cast.ToTime() uses UTC instead of Local to be consistent with time.Now(). Thanks.

  1. Use the following code snippet:

import (
	"fmt"
	"time"

	"github.com/spf13/cast"
)

func main() {
	timeStr := "2024-09-09 20:46:05"
	t1 := cast.ToTime(timeStr)
	fmt.Println("cast.ToTime -> ", t1)

	now := time.Now()
	fmt.Println("time.Now() -> ", now)

	fmt.Println("now.After", now.After(t1))
}

  1. The output is:
cast.ToTime ->  2024-09-09 20:46:05 +0000 UTC
time.Now() ->  2024-09-09 21:59:33.889463 +0800 CST m=+0.000234554
now.After false

Here are the definitions of caste and time

// caste.go
// ToTimeE casts an interface to a time.Time type.
func ToTimeE(i interface{}) (tim time.Time, err error) {
	return ToTimeInDefaultLocationE(i, time.UTC)
}

// time.go
// Now returns the current local time.
func Now() Time {
	sec, nsec, mono := now()
	mono -= startNano
	sec += unixToInternal - minWall
	if uint64(sec)>>33 != 0 {
		return Time{uint64(nsec), sec + minWall, Local}
	}
	return Time{hasMonotonic | uint64(sec)<<nsecShift | uint64(nsec), mono, Local}
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reading ToTimeE in caste.go and comparing its UTC default with the local-time behavior shown for time.Now in time.go. Reproduce the supplied example and determine the intended timezone semantics for parsed strings. Done requires a maintainer-confirmed decision, with the behavior or documentation made consistent and verified by appropriate tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.