Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow tranforming LocalTime to time.Duration #969

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions localtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ type LocalTime struct {
Precision int // Number of digits to display for Nanosecond.
}

// AsDuration converts d into a duration
func (d LocalTime) AsDuration() time.Duration {
return time.Duration(d.Hour)*time.Hour + time.Duration(d.Minute)*time.Minute + time.Duration(d.Second)*time.Second + time.Duration(d.Nanosecond)*time.Nanosecond
}

// String returns RFC 3339 representation of d.
// If d.Nanosecond and d.Precision are zero, the time won't have a nanosecond
// component. If d.Nanosecond > 0 but d.Precision = 0, then the minimum number
Expand Down
1 change: 1 addition & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
)

var timeType = reflect.TypeOf((*time.Time)(nil)).Elem()
var durationType = reflect.TypeOf((*time.Duration)(nil)).Elem()
var textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
var textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
var mapStringInterfaceType = reflect.TypeOf(map[string]interface{}(nil))
Expand Down
6 changes: 6 additions & 0 deletions unmarshaler.go
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,12 @@ func (d *decoder) unmarshalLocalTime(value *unstable.Node, v reflect.Value) erro
return unstable.NewParserError(rest, "extra characters at the end of a local time")
}

if v.Type() == durationType {
cast := lt.AsDuration()
v.Set(reflect.ValueOf(cast))
return nil
}

v.Set(reflect.ValueOf(lt))
return nil
}
Expand Down
14 changes: 14 additions & 0 deletions unmarshaler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,20 @@ foo = "bar"`,
}
},
},
{
desc: "local-time into duration",
input: `a = 12:08:05.666666666`,
gen: func() test {
var v map[string]time.Duration

return test{
target: &v,
expected: &map[string]time.Duration{
"a": 12*time.Hour + 8*time.Minute + 5*time.Second + 666666666*time.Nanosecond, //toml.LocalTime{Hour: 12, Minute: 8, Second: 5, Nanosecond: 666666666, Precision: 9},
},
}
},
},
{
desc: "local-time missing digit",
input: `a = 12:08:0`,
Expand Down