github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/commons/times/parse.go (about) 1 /* 2 * Copyright 2023 Wang Min Xiang 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 * 16 */ 17 18 package times 19 20 import ( 21 "fmt" 22 "strings" 23 "time" 24 ) 25 26 func ParseTime(value string) (result time.Time, err error) { 27 value = strings.TrimSpace(value) 28 if value == "" { 29 result = time.Time{} 30 return 31 } 32 if len(value) == 10 { 33 result, err = time.Parse("2006-01-02", value) 34 return 35 } 36 if len(value) == len(time.RFC3339) { 37 result, err = time.Parse(time.RFC3339, value) 38 return 39 } 40 if len(value) == len(time.RFC3339Nano) { 41 result, err = time.Parse(time.RFC3339Nano, value) 42 return 43 } 44 if len(value) == 19 { 45 if strings.IndexByte(value, 'T') > 0 { 46 result, err = time.Parse("2006-01-02T15:04:05", value) 47 } else { 48 result, err = time.Parse("2006-01-02 15:04:05", value) 49 } 50 return 51 } 52 if len(value) > 19 && strings.IndexByte(value, 'T') > 0 && strings.IndexByte(value, 'Z') > 0 { 53 if strings.IndexByte(value, 'T') > 0 && strings.IndexByte(value, 'Z') > 0 { 54 // ISO8601 55 result, err = time.Parse("2006-01-02T15:04:05.000Z0700", value) 56 } else { 57 result, err = time.Parse("2006-01-02 15:04:05.999999999-07:00", value) 58 59 } 60 return 61 } 62 63 err = fmt.Errorf("parse %s to time failed, layout is not supported", value) 64 65 return 66 }