summaryrefslogtreecommitdiff
path: root/time.go
blob: fb2eeb749de7fcf38e0137d5180e76c3daf977ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package cobol

import (
	"errors"
	"fmt"
	"time"

	"google.golang.org/protobuf/types/known/timestamppb"
)

// you will be happier if you just use this everywhere
// This is always 22 chars
func Time(someTimeAgoOrLaterNotsure any) string {
	guess, t, err := TimeCheck(someTimeAgoOrLaterNotsure)
	// this should probably be done first
	if t != nil {
		return FormatTime(*t)
	}
	if len(guess) > 0 {
		return fmt.Sprintf("%-22.22s", guess)
	}
	if errors.Is(err, Broken) {
		return fmt.Sprintf("%-22.22s", "cobol.Time() Broken")
	}
	if errors.Is(err, NoTime) {
		return fmt.Sprintf("%-22.22s", "cobol.Time() NoTime")
	}
	return fmt.Sprintf("%-22.22s", " / /  : :  (notsure)")
}

func isUTC(t time.Time) bool {
	return t.Location() == time.UTC
}

func TimeLocal(someTimeAgoOrLaterNotsure any) string {
	guess, t, err := TimeCheck(someTimeAgoOrLaterNotsure)
	if errors.Is(err, Broken) {
		if len(guess) > 0 {
			return fmt.Sprintf("%-15s", guess)
		}
		return "bad"
	}
	if errors.Is(err, NoTime) {
		if len(guess) > 0 {
			return fmt.Sprintf("%-15s", guess)
		}
		return "nope"
	}
	return FormatTimeLocal(*t)
}

func GetTime(mightBeTimeMightNotBeTime any) (*time.Time, error) {
	_, t, err := TimeCheck(mightBeTimeMightNotBeTime)
	return t, err
}

func TimeCheck(maybeTime any) (string, *time.Time, error) {
	var guess string
	var t *time.Time
	var err error

	switch v := maybeTime.(type) {
	case time.Time:
		// If the type is time.Time, 'v' is now a time.Time variable.
		// t = v
		return FormatTime(v), &v, err
	case string:
		// The type is string, so 'v' is a string variable.
		t, err = doTimeString(v)
		if t != nil {
			return "", t, err
		}
		if err != nil {
			guess = v
		}
	case *timestamppb.Timestamp:
		// If it's a protobuf Timestamp pointer (most common case),
		// 'v' is a *timestamppb.Timestamp. We must convert it.
		// It's also good to check if it's a valid timestamp.
		if v.IsValid() {
			newt := v.AsTime()
			return FormatTime(newt), &newt, nil
		} else {
			err = errors.New("pb time invalid")
		}

	case timestamppb.Timestamp:
		// Handle the less common case of a value type instead of a pointer.
		if v.IsValid() {
			newt := v.AsTime()
			return FormatTime(newt), &newt, nil
		}
	default:
		err = errors.Join(err, NoTime)
	}
	return guess, t, err
}