...
▽

Source file src/golang.conradwood.net/go-easyops/utils/clock_utils.go

Documentation: golang.conradwood.net/go-easyops/utils

     1  package utils
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  )
     8  
     9  // true if current hour is between a and b
    10  // clock is 24 hours
    11  // overflow is ok, e.g. CurrentHourCheck(22,8) will return true at night
    12  // always refers to local time
    13  func CurrentHourCheck(a, b int) bool {
    14  	t, err := LocalTime(context.Background())
    15  	if err != nil {
    16  		fmt.Printf("failed to get localtime: %s\n", ErrorString(err))
    17  		return false
    18  	}
    19  	return currentHourCheckWithTime(a, b, t)
    20  }
    21  
    22  func currentHourCheckWithTime(a, b int, t time.Time) bool {
    23  	h, _, _ := t.Clock()
    24  	if a == b {
    25  		// e.g. CurrentHourCheck(22,22) -> returns true only at 22 hours
    26  		return h == a
    27  	}
    28  
    29  	if a > b {
    30  		// e.g. CurrentHourCheck(22,8) -> returns true between 22 and 8 hours (as in: during the night)
    31  		if h >= a {
    32  			return true
    33  		}
    34  		if h < b {
    35  			return true
    36  		}
    37  		return false
    38  	}
    39  
    40  	// e.g. CurrentHourCheck(8,22) -> returns true between 8 and 22 hours (as in: during the day)
    41  	if h <= a {
    42  		return false
    43  	}
    44  	if h > b {
    45  		return false
    46  	}
    47  	return true
    48  }
    49  

View as plain text