v8.run/go/exp@v0.0.26-0.20230226010534-afcdbd3f782d/time2/parse.go (about)

     1  package time2
     2  
     3  import (
     4  	"time"
     5  
     6  	"v8.run/go/exp/time2/timeparse"
     7  )
     8  
     9  type DateTime struct {
    10  	unix int64
    11  	nano int64
    12  }
    13  
    14  func FromTime(t time.Time) DateTime {
    15  	u := t.Unix()
    16  	n := t.Nanosecond()
    17  	return DateTime{u, int64(n)}
    18  }
    19  
    20  func FromUnix(unix int64) DateTime {
    21  	return DateTime{unix, 0}
    22  }
    23  
    24  func FromUnixAndNano(unix, nano int64) DateTime {
    25  	return DateTime{unix, nano}
    26  }
    27  
    28  func FromUnixNano(unixNano int64) DateTime {
    29  	return DateTime{unixNano / 1e9, unixNano % 1e9}
    30  }
    31  
    32  func Now() DateTime {
    33  	return FromTime(time.Now())
    34  }
    35  
    36  func Time(v ...string) DateTime {
    37  	data := v[0]
    38  
    39  	if len(v) == 0 || len(v[0]) == 0 {
    40  		return Now()
    41  	}
    42  
    43  	if len(v) == 1 {
    44  		unix, nano, _ := timeparse.Parse8601(data)
    45  		return DateTime{unix, nano}
    46  	}
    47  
    48  	return DateTime{}
    49  }
    50  
    51  func (dt DateTime) String() string {
    52  	return time.Unix(dt.unix, 0).Format(time.RFC3339)
    53  }
    54  
    55  func (dt DateTime) Unix() int64 {
    56  	return dt.unix
    57  }
    58  
    59  func (dt DateTime) ToTime() time.Time {
    60  	return time.Unix(dt.unix, dt.nano)
    61  }