github.com/blend/go-sdk@v1.20220411.3/timeutil/parse_time.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package timeutil
     9  
    10  import "time"
    11  
    12  // Extra time formats
    13  const (
    14  	TimeFormatCompleteDate24TimeUTC      = "2006-01-02 15:04Z07:00"
    15  	TimeFormatCompleteDate24TimeUTCSlash = "2006/01/02 15:04Z07:00"
    16  	TimeFormatCompleteDate               = "2006-01-02"
    17  	TimeFormatCompleteDateSlash          = "2006/01/02"
    18  	TimeFormatKitchen24                  = "15:04"
    19  )
    20  
    21  var (
    22  	// DefaultTimeFormats are the default time formats used in parsing.
    23  	// They are ordered from _most_ specific to least specific.
    24  	DefaultTimeFormats = []string{
    25  		time.RFC3339Nano,
    26  		time.RFC3339,
    27  		TimeFormatCompleteDate24TimeUTC,
    28  		TimeFormatCompleteDate24TimeUTCSlash,
    29  		TimeFormatCompleteDate,
    30  		TimeFormatCompleteDateSlash,
    31  		TimeFormatKitchen24,
    32  		time.Kitchen,
    33  	}
    34  )
    35  
    36  // ParseTimeDefaults parses a time string with the default time formats.
    37  func ParseTimeDefaults(timeStr string) (time.Time, error) {
    38  	return ParseTime(timeStr, DefaultTimeFormats...)
    39  }
    40  
    41  // ParseTime parses a time string with a given set of formats.
    42  func ParseTime(timeStr string, timeFormats ...string) (output time.Time, err error) {
    43  	for _, timeFormat := range timeFormats {
    44  		output, err = time.Parse(timeFormat, timeStr)
    45  		if err == nil && !output.IsZero() {
    46  			return
    47  		}
    48  	}
    49  	return
    50  }