Skip to content

Commit

Permalink
Merge pull request #401 from israelviana/main
Browse files Browse the repository at this point in the history
convert date time to brazil format
  • Loading branch information
armando-couto authored Nov 22, 2023
2 parents 205cf43 + d85493c commit d8165bc
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions datetime.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package goutils

import (
"errors"
"fmt"
"reflect"
"strings"
"time"
)
Expand Down Expand Up @@ -257,3 +260,59 @@ func WeekEndDate(date time.Time) time.Time {
result := date.Add(time.Duration(offset*24) * time.Hour)
return result
}

func ConvertDateToBrazilFormat(date any) (string, error) {
formats := []string{
"0001-01-01",
"02012006",
"02/01/2006",
"02/01/2006 15:04:05",
"2006-01-02 15:04:05",
"01-02-2006 15:04",
"20060102",
"060102150405",
"20060102150405",
"200601",
"2006-01-02",
"060102",
"150405",
"15",
"15:04:05",
"2006-01-02 15:04:05",
"02-01-2006",
}

typeDate := reflect.TypeOf(date)
var dateConverted string

switch typeDate.Kind() {
case reflect.String:
dateString := date.(string)
if strings.TrimSpace(dateString) != "" {
if strings.ContainsAny(dateString, "T") {
dateString = strings.Split(dateString, "T")[0]
}

for _, format := range formats {
t, err := time.Parse(format, dateString)

if err == nil {
dateConverted = t.Format("02/01/2006")
return dateConverted, nil
}
}
} else if strings.TrimSpace(dateString) == "" {
return "", nil
}
return "", errors.New(fmt.Sprint("error to convert date" + dateString))

case reflect.Struct:
if typeDate == reflect.TypeOf(time.Time{}) {
dateConverted = date.(time.Time).Format("02/01/2006")
}
default:
return "", errors.New("error to convert date; time is unknown")
}

return dateConverted, nil
}

0 comments on commit d8165bc

Please sign in to comment.