summaryrefslogtreecommitdiffstats
path: root/time
diff options
context:
space:
mode:
authorsiddharth ravikumar <s@ricketyspace.net>2022-08-06 23:19:40 -0400
committersiddharth ravikumar <s@ricketyspace.net>2022-08-06 23:19:40 -0400
commit5ddc92c3556bf04e019a77e7242440e3defd5555 (patch)
tree658ff8e319b6daf0e442859caca01743632f578b /time
parentb6d64f1c9c2113601d6b920d9b53a644669357cf (diff)
time: add `IsCurrent`
Diffstat (limited to 'time')
-rw-r--r--time/time.go36
-rw-r--r--time/time_test.go27
2 files changed, 62 insertions, 1 deletions
diff --git a/time/time.go b/time/time.go
index 37ecdbb..89847ab 100644
--- a/time/time.go
+++ b/time/time.go
@@ -8,6 +8,7 @@ import (
"fmt"
"regexp"
"strconv"
+ "strings"
"time"
)
@@ -46,4 +47,39 @@ func Duration(duration string) (time.Duration, error) {
return d, nil
}
+
+// Checks if the given ISO 8601 time is within the current time
+// period.
+//
+// `t` must be in 2022-08-07T02:00:00+00:00/PT1H format
+//
+// Returns true if the time `t` is the current time period; false
+// otherwise.
+func IsCurrent(t string) (bool, error) {
+ parts := strings.Split(t, "/")
+ if len(parts) != 2 {
+ return false, fmt.Errorf("time invalid")
+ }
+
+ // Parse time `t` into time intervals t1 and t2.
+ t1, err := time.Parse(time.RFC3339, parts[0])
+ if err != nil {
+ return false, fmt.Errorf("time invalid: %s", err)
+ }
+ d, err := Duration(parts[1])
+ if err != nil {
+ return false, fmt.Errorf("time invalid: %s", err)
+ }
+ t2 := t1.Add(d)
+
+ // Time `t` is in the current time period if current time is
+ // within the interval t1 and t2.
+ now := time.Now()
+ if t1.Before(now) && now.Before(t2) {
+ return true, nil
+ }
+ if t1.Equal(now) || t2.Equal(now) {
+ return true, nil
+ }
+ return false, nil
}
diff --git a/time/time_test.go b/time/time_test.go
index 5bb6cb2..efb3078 100644
--- a/time/time_test.go
+++ b/time/time_test.go
@@ -3,7 +3,11 @@
package time
-import "testing"
+import (
+ "fmt"
+ "testing"
+ "time"
+)
func TestDurationToSeconds(t *testing.T) {
d, err := Duration("PT3H4M60S")
@@ -66,3 +70,24 @@ func TestDurationToSeconds(t *testing.T) {
return
}
}
+
+func TestIsCurrent(t *testing.T) {
+ yes, err := IsCurrent("2022-08-07T01:00:00+00:00/PT1H")
+ if yes || err != nil {
+ t.Errorf("iscurrent failed: %v: %v", yes, err)
+ return
+ }
+
+ h, err := time.ParseDuration("-3600s")
+ if err != nil {
+ t.Errorf("-3600s parsing duration: %v", err)
+ return
+ }
+ ts := time.Now().Add(h).UTC().Format(time.RFC3339)
+ yes, err = IsCurrent(fmt.Sprintf("%s+00:00/PT2H", ts[:len(ts)-1]))
+ if !yes || err != nil {
+ t.Errorf("iscurrent failed: %v: %v", yes, err)
+ return
+ }
+
+}