...

Source file src/edge-infra.dev/pkg/lib/edgeutils/datetime_helper.go

Documentation: edge-infra.dev/pkg/lib/edgeutils

     1  package edgeutils
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"time"
     7  )
     8  
     9  func IsValidTimestamp(time string) error {
    10  	// ISO 8601 regex
    11  	validRegex := "^(-?(?:[1-9][0-9]*)?[0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])(?:T|\\s)(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])?(Z)?$"
    12  	compiledRegex := regexp.MustCompile(validRegex)
    13  
    14  	if !compiledRegex.MatchString(time) {
    15  		return fmt.Errorf("Timestamp %s is not a valid Timestamp", time)
    16  	}
    17  	return nil
    18  }
    19  
    20  func TimeSequenceCheck(start string, end string) error {
    21  	// EX: 2024-04-25T15:34:12Z
    22  	timeInputStart, err := time.Parse(time.RFC3339, start)
    23  	if err != nil {
    24  		return fmt.Errorf("Start Timestamp %s was not able to be parsed as a Time Object", start)
    25  	}
    26  
    27  	timeInputEnd, err := time.Parse(time.RFC3339, end)
    28  	if err != nil {
    29  		return fmt.Errorf("End Timestamp %s was not able to be parsed as a Time Object", end)
    30  	}
    31  
    32  	if timeInputEnd.Before(timeInputStart) {
    33  		return fmt.Errorf("End Timestamp %s comes before the start time %s", end, start)
    34  	}
    35  	return nil
    36  }
    37  
    38  func ConvertToRFC3339(timeInput string) (string, error) {
    39  	// input := "2024-05-01T08:04:12-04:00"
    40  	loc, _ := time.LoadLocation("UTC")
    41  	expected, err := time.Parse(time.RFC3339, timeInput)
    42  	if err != nil {
    43  		return "", fmt.Errorf("Date Formatting Error: %w", err)
    44  	}
    45  	res := expected.In(loc)
    46  
    47  	newRes := res.Format(time.RFC3339)
    48  
    49  	return newRes, nil
    50  }
    51  

View as plain text