package datatypes
import (
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"gorm.io/gorm"
"gorm.io/gorm/schema"
)
type Time time .Duration
func NewTime (hour , min , sec , nsec int ) Time {
return newTime (hour , min , sec , nsec )
}
func newTime(hour , min , sec , nsec int ) Time {
return Time (
time .Duration (hour )*time .Hour +
time .Duration (min )*time .Minute +
time .Duration (sec )*time .Second +
time .Duration (nsec )*time .Nanosecond ,
)
}
func (Time ) GormDataType () string {
return "time"
}
func (Time ) GormDBDataType (db *gorm .DB , field *schema .Field ) string {
switch db .Dialector .Name () {
case "mysql" :
return "TIME"
case "postgres" :
return "TIME"
case "sqlserver" :
return "TIME"
case "sqlite" :
return "TEXT"
default :
return ""
}
}
func (t *Time ) Scan (src interface {}) error {
switch v := src .(type ) {
case []byte :
t .setFromString (string (v ))
case string :
t .setFromString (v )
case time .Time :
t .setFromTime (v )
default :
return errors .New (fmt .Sprintf ("failed to scan value: %v" , v ))
}
return nil
}
func (t *Time ) setFromString (str string ) {
var h , m , s , n int
fmt .Sscanf (str , "%02d:%02d:%02d.%09d" , &h , &m , &s , &n )
*t = newTime (h , m , s , n )
}
func (t *Time ) setFromTime (src time .Time ) {
*t = newTime (src .Hour (), src .Minute (), src .Second (), src .Nanosecond ())
}
func (t Time ) Value () (driver .Value , error ) {
return t .String (), nil
}
func (t Time ) String () string {
if nsec := t .nanoseconds (); nsec > 0 {
return fmt .Sprintf ("%02d:%02d:%02d.%09d" , t .hours (), t .minutes (), t .seconds (), nsec )
} else {
return fmt .Sprintf ("%02d:%02d:%02d" , t .hours (), t .minutes (), t .seconds ())
}
}
func (t Time ) hours () int {
return int (time .Duration (t ).Truncate (time .Hour ).Hours ())
}
func (t Time ) minutes () int {
return int ((time .Duration (t ) % time .Hour ).Truncate (time .Minute ).Minutes ())
}
func (t Time ) seconds () int {
return int ((time .Duration (t ) % time .Minute ).Truncate (time .Second ).Seconds ())
}
func (t Time ) nanoseconds () int {
return int ((time .Duration (t ) % time .Second ).Nanoseconds ())
}
func (t Time ) MarshalJSON () ([]byte , error ) {
return json .Marshal (t .String ())
}
func (t *Time ) UnmarshalJSON (data []byte ) error {
if string (data ) == "null" {
return nil
}
t .setFromString (strings .Trim (string (data ), `"` ))
return nil
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .