mirror of
https://gitee.com/johng/gf.git
synced 2024-12-02 04:07:47 +08:00
improve package gtime
This commit is contained in:
parent
2c0cfa24b0
commit
d4d66fd529
@ -11,6 +11,7 @@ package gtime
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/gogf/gf/errors/gerror"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -233,10 +234,12 @@ func StrToTime(str string, format ...string) (*Time, error) {
|
||||
if len(format) > 0 {
|
||||
return StrToTimeFormat(str, format[0])
|
||||
}
|
||||
var year, month, day int
|
||||
var hour, min, sec, nsec int
|
||||
var match []string
|
||||
var local = time.Local
|
||||
var (
|
||||
year, month, day int
|
||||
hour, min, sec, nsec int
|
||||
match []string
|
||||
local = time.Local
|
||||
)
|
||||
if match = timeRegex1.FindStringSubmatch(str); len(match) > 0 && match[1] != "" {
|
||||
for k, v := range match {
|
||||
match[k] = strings.TrimSpace(v)
|
||||
@ -282,6 +285,9 @@ func StrToTime(str string, format ...string) (*Time, error) {
|
||||
h, _ := strconv.Atoi(zone[0:2])
|
||||
m, _ := strconv.Atoi(zone[2:4])
|
||||
s, _ := strconv.Atoi(zone[4:6])
|
||||
if h > 24 || m > 59 || s > 59 {
|
||||
return nil, gerror.Newf("invalid zone string: %s", match[6])
|
||||
}
|
||||
// Comparing the given time zone whether equals to current tine zone,
|
||||
// it converts it to UTC if they does not.
|
||||
_, localOffset := time.Now().Zone()
|
||||
|
@ -67,6 +67,9 @@ var (
|
||||
|
||||
// Format formats and returns the formatted result with custom <format>.
|
||||
func (t *Time) Format(format string) string {
|
||||
if t == nil {
|
||||
return ""
|
||||
}
|
||||
runes := []rune(format)
|
||||
buffer := bytes.NewBuffer(nil)
|
||||
for i := 0; i < len(runes); {
|
||||
|
@ -43,6 +43,7 @@ func NewFromTime(t time.Time) *Time {
|
||||
}
|
||||
|
||||
// NewFromStr creates and returns a Time object with given string.
|
||||
// Note that it returns nil if there's error occurs.
|
||||
func NewFromStr(str string) *Time {
|
||||
if t, err := StrToTime(str); err == nil {
|
||||
return t
|
||||
@ -52,6 +53,7 @@ func NewFromStr(str string) *Time {
|
||||
|
||||
// NewFromStrFormat creates and returns a Time object with given string and
|
||||
// custom format like: Y-m-d H:i:s.
|
||||
// Note that it returns nil if there's error occurs.
|
||||
func NewFromStrFormat(str string, format string) *Time {
|
||||
if t, err := StrToTimeFormat(str, format); err == nil {
|
||||
return t
|
||||
@ -61,6 +63,7 @@ func NewFromStrFormat(str string, format string) *Time {
|
||||
|
||||
// NewFromStrLayout creates and returns a Time object with given string and
|
||||
// stdlib layout like: 2006-01-02 15:04:05.
|
||||
// Note that it returns nil if there's error occurs.
|
||||
func NewFromStrLayout(str string, layout string) *Time {
|
||||
if t, err := StrToTimeLayout(str, layout); err == nil {
|
||||
return t
|
||||
|
Loading…
Reference in New Issue
Block a user