other days (tue - sun) omitted for brevity. The integer is a UNIX timestamp.
The objects are half intervals, so only the opening time or closing time is present in the object, but not both.
The data is valid (e.g. for every open object, there is a corresponding close object). There can be multiple intervals within the day.
I need to make an intersection of the times so that if a is open from 5 to 9 and b is open from 5 to 8, the intersection will be from 5 to 8.
I have the following structs:
type OperatingTime struct {
Open *int json:"open"
Close *int json:"close"
}
The closing time can be on the next day. So if I open on Monday at 20:00, the Close object can be present on Tuesday's Close array as the first element, like so:
Yes, the UNIX timestamp is for the current day (the date part is 1.1.1970).
Assistant
You basically need to:
Convert each day's list of half-intervals (just open or close timestamps) into a proper list of intervals [start, end].
Compute the intersection of intervals for each day between API a and API b.
Return the intersection intervals, possibly converted back to your original data style if needed.
Step 1: Convert half-interval objects into full intervals for each day
Each day's slice is a sequence of {Open: x}, {Close: y}, {Open: x2}, {Close: y2}, ... pairs. You want to parse into:
go
type Interval struct {
Start int
End int
}
A utility function for this:
go
func buildIntervals(times []OperatingTime) []Interval {
var intervals []Interval
var start int
openFound := false
for _, ot := range times {
if ot.Open != nil {
start = *ot.Open
openFound = true
} else if ot.Close != nil && openFound {
intervals = append(intervals, Interval{Start: start, End: *ot.Close})
openFound = false
}
}
return intervals
}
Step 2: Compute intersection of two slices of intervals for a single day
Intervals in each slice are presumably non-overlapping and sorted, so you can do a merge-like intersection:
go
func intersectIntervals(a, b []Interval) []Interval {
i, j := 0, 0
var result []Interval
for i < len(a) && j < len(b) {
// Calculate overlap
start := max(a[i].Start, b[j].Start)
end := min(a[i].End, b[j].End)
if start < end {
// There is an overlap
result = append(result, Interval{Start: start, End: end})
}
// Move the pointer which ends first
if a[i].End < b[j].End {
i++
} else {
j++
}
}
return result
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Step 3: Process all days
You'll want to iterate over all days, transform their half-interval arrays to interval arrays, compute intersection, then output result.
Step 4 (optional): Convert intervals back to your format
If you want to output intervals back as half-interval OperatingTime slices:
go
func intervalsToOperatingTime(intervals []Interval) []OperatingTime {
var result []OperatingTime
for _, iv := range intervals {
o := iv.Start
c := iv.End
result = append(result, OperatingTime{Open: &o})
result = append(result, OperatingTime{Close: &c})
}
return result
}
This approach is clean, simple, and efficient (O(n+m) per day).
If you want, I can help write a complete working example with your structs. Just ask!
Thanks for the extra constraint! This means intervals can span midnight and thus their close timestamp is on the next day, potentially appearing as a close record in the next day's slice.
This adds complexity because your daily arrays are half-interval fragments split by day boundaries that may not align with the actual open-close intervals.
Key insight
Your data for each day is chunked by the API's "day", but intervals may span midnight and be split across days.
You cannot just parse each day's array independently; you need to process the entire week's data as a continuous timeline to correctly pair open-close regardless of day boundaries.
After reconstructing full intervals for the whole week (possibly overlapping midnight boundaries), you can split those intervals back into daily intervals or treat them as spanning multiple days internally.
Then apply intersection logic on the correctly reconstructed intervals.
Suggested approach
Step 1: Preprocessing: Flatten all days into one timeline
Combine all daily OperatingTime slices into one list, ordered by their timestamps.
You'll need to maintain info about which day the half-interval belongs to, primarily for reconstructing results or clarity, but the timestamps themselves should be interpreted as absolute over the week.
But wait
You said timestamps are UNIX timestamps, which are absolute points in time across days, not relative seconds-of-day.
If the open on Monday 20:00 is 72000, and the close on Tuesday 01:00 is 3600, these seem to be seconds since midnight of their respective days (otherwise, the close on Tuesday would be smaller than the open on Monday).
So they're per-day seconds (seconds since midnight), not absolute UNIX timestamps! This requires:
You must treat the times as per-day offsets.
You must know which day is which.
To make a continuous timeline, you can convert day + seconds into an absolute timestamp relative to week start.
Step 2: Define day offsets
Assume:
Monday = day 0
Tuesday = day 1
...
Sunday = day 6
Since one day = 86400 seconds, you can calculate an absolute timestamp for every open or close as:
Step 3: Convert all OperatingTime to absolute intervals over the week
You will need to process the whole week data of one API at once:
For each day (Monday to Sunday) with index d:
For each half interval:
If Open, absolute open time = d*86400 + open
If Close, absolute close time = d*86400 + close
Since the close might be on the next day (like in your example):
The close half-interval may appear as the first one on day d+1, while the open is on day d.
The OperatingTime arrays per day most likely appear as consecutive {open}, {close}, {open}, {close} pairs logically, but split by day boundaries.
Step 4: Join split intervals across days
To reconstruct intervals (now with absolute timestamps) correctly:
Iterate days Monday to Sunday in order.
Within each day, iterate over the day's OperatingTime slice sequentially.
Keep track of an outstanding open time (absolute value).
When you see an open half-interval: record absolute open time.
When you see a close half-interval: with absolute close time, pair with the last open if any, form one interval [open, close].
If the close is on the next day (because the close half interval is the first element of day d+1), this scheme still works — because you proceed day by day, you'll pair it when processing the next day.
Step 5: Build helper function to flatten one week's Hours into []Interval with absolute unix offsets
Step 6: Intersect intervals of API a and API b as before (on absolute timestamps).
Step 7: After intersection, you may want to split back intervals into days — or leave them in absolute form.
Splitting back can be done by slicing intervals at day boundaries (every 86400 seconds).
For each interval that overlaps multiple days, split accordingly.
Example code skeleton for flattening one week API's Hours to intervals
go
type Interval struct {
Start int // absolute time in seconds relative to week start
End int
}
// map string day name to index
var dayToIndex = map[string]int{
"monday": 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6,
}
// Helper to get slice of OperatingTimes by day name
func getDayOps(h Hours, day string) []OperatingTime {
switch day {
case "monday": return h.Monday
case "tuesday": return h.Tuesday
case "wednesday": return h.Wednesday
case "thursday": return h.Thursday
case "friday": return h.Friday
case "saturday": return h.Saturday
case "sunday": return h.Sunday
}
return nil
}
// flattenHours converts one week's Hours to a slice of absolute Intervals
func flattenHours(h Hours) []Interval {
days := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
var intervals []Interval
openPending := -1
for _, day := range days {
dayIndex := dayToIndex[day]
times := getDayOps(h, day)
for _, ot := range times {
if ot.Open != nil {
// absolute open time
openPending = dayIndex*86400 + *ot.Open
} else if ot.Close != nil && openPending != -1 {
closeTime := dayIndex*86400 + *ot.Close
intervals = append(intervals, Interval{Start: openPending, End: closeTime})
openPending = -1
} else {
// inconsistency - close with no open. Should not happen if data valid.
}
}
}
return intervals
}
Split intervals back to daily OperatingTime (optional)
If you want to output the intersection per day again, you have to:
For each interval, check which days it overlaps.
Chop intervals if they cross midnight boundary.
For each day, convert interval(s) to OperatingTime half intervals with seconds since midnight (absolute time % 86400).
Example:
go
func splitIntervalsToDays(intervals []Interval) Hours {
days := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
result := Hours{}
for _, interval := range intervals {
startDayIdx := interval.Start / 86400
endDayIdx := (interval.End - 1) / 86400 // minus 1 to handle exact midnight ends
for d := startDayIdx; d <= endDayIdx; d++ {
dayStartAbs := d * 86400
dayEndAbs := dayStartAbs + 86400
// clip interval to day boundaries
start := max(interval.Start, dayStartAbs)
end := min(interval.End, dayEndAbs)
otSlice := []OperatingTime{
{Open: ptr(start - dayStartAbs)},
{Close: ptr(end - dayStartAbs)},
}
// assign to correct day slice
switch days[d] {
case "monday":
result.Monday = append(result.Monday, otSlice...)
case "tuesday":
result.Tuesday = append(result.Tuesday, otSlice...)
case "wednesday":
result.Wednesday = append(result.Wednesday, otSlice...)
case "thursday":
result.Thursday = append(result.Thursday, otSlice...)
case "friday":
result.Friday = append(result.Friday, otSlice...)
case "saturday":
result.Saturday = append(result.Saturday, otSlice...)
case "sunday":
result.Sunday = append(result.Sunday, otSlice...)
}
}
}
return result
}
func ptr(i int) *int {
v := i
return &v
}
Convert days+times into absolute seconds in the week (with day*86400).
Build intervals across day boundaries from flat data.
Intersect absolute intervals.
Optionally, split intervals back to per-day half-interval data.
If you want I can also help with a full working example program. Just ask!
Thanks for confirming that the UNIX timestamps in your data are seconds since midnight of the "current" day (i.e., relative timestamps). This means your values are offsets within a day (0–86399 or more) without the date part.
What this means:
You must treat the daily timestamps as seconds of day.
To handle cross-day intervals properly, you need to combine day + time into an absolute timeline for the entire week by adding dayIndex * 86400.
So Monday 20:00 = 72000 + 0 * 86400 = 72000
Tuesday 01:00 = 3600 + 1 * 86400 = 90000 (correctly after Monday's open of 72000).
Complete example Go code to handle your use case:
I’ll provide a full example snippet showing:
How to parse the weekly data into absolute intervals (cross-day intervals supported).
Intersect them.
Convert result back per day.
go
package main
import (
"fmt"
)
type OperatingTime struct {
Open *int `json:"open"`
Close *int `json:"close"`
}
type Hours struct {
Monday []OperatingTime `json:"monday"`
Tuesday []OperatingTime `json:"tuesday"`
Wednesday []OperatingTime `json:"wednesday"`
Thursday []OperatingTime `json:"thursday"`
Friday []OperatingTime `json:"friday"`
Saturday []OperatingTime `json:"saturday"`
Sunday []OperatingTime `json:"sunday"`
}
type Interval struct {
Start int // absolute seconds relative to week start (Monday 00:00)
End int
}
var dayToIndex = map[string]int{
"monday": 0,
"tuesday": 1,
"wednesday": 2,
"thursday": 3,
"friday": 4,
"saturday": 5,
"sunday": 6,
}
func ptr(i int) *int {
v := i
return &v
}
// get day slice from Hours by name
func getDayOps(h Hours, day string) []OperatingTime {
switch day {
case "monday":
return h.Monday
case "tuesday":
return h.Tuesday
case "wednesday":
return h.Wednesday
case "thursday":
return h.Thursday
case "friday":
return h.Friday
case "saturday":
return h.Saturday
case "sunday":
return h.Sunday
}
return nil
}
// flattenHours converts weekly Hours to a slice of absolute Intervals across the week
func flattenHours(h Hours) []Interval {
days := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
var intervals []Interval
openPending := -1
for _, day := range days {
dayIndex := dayToIndex[day]
times := getDayOps(h, day)
for _, ot := range times {
if ot.Open != nil {
openPending = dayIndex*86400 + *ot.Open
} else if ot.Close != nil && openPending != -1 {
closeTime := dayIndex*86400 + *ot.Close
intervals = append(intervals, Interval{Start: openPending, End: closeTime})
openPending = -1
}
}
}
return intervals
}
// intersectIntervals computes intersection of two interval lists
func intersectIntervals(a, b []Interval) []Interval {
i, j := 0, 0
var result []Interval
for i < len(a) && j < len(b) {
start := max(a[i].Start, b[j].Start)
end := min(a[i].End, b[j].End)
if start < end {
result = append(result, Interval{Start: start, End: end})
}
if a[i].End < b[j].End {
i++
} else {
j++
}
}
return result
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
// splitIntervalsToDays splits absolute intervals back into Days with half-intervals
func splitIntervalsToDays(intervals []Interval) Hours {
days := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
result := Hours{}
for _, iv := range intervals {
startDay := iv.Start / 86400
endDay := (iv.End - 1) / 86400 // to handle exact midnight correctly
for d := startDay; d <= endDay; d++ {
dayStartAbs := d * 86400
dayEndAbs := dayStartAbs + 86400
// clip interval to current day boundaries
start := max(iv.Start, dayStartAbs)
end := min(iv.End, dayEndAbs)
otSlice := []OperatingTime{
{Open: ptr(start - dayStartAbs)},
{Close: ptr(end - dayStartAbs)},
}
switch days[d] {
case "monday":
result.Monday = append(result.Monday, otSlice...)
case "tuesday":
result.Tuesday = append(result.Tuesday, otSlice...)
case "wednesday":
result.Wednesday = append(result.Wednesday, otSlice...)
case "thursday":
result.Thursday = append(result.Thursday, otSlice...)
case "friday":
result.Friday = append(result.Friday, otSlice...)
case "saturday":
result.Saturday = append(result.Saturday, otSlice...)
case "sunday":
result.Sunday = append(result.Sunday, otSlice...)
}
}
}
return result
}
// Main intersection function for two Hours with cross-day intervals
func intersectHoursCrossDay(a, b Hours) Hours {
aIntervals := flattenHours(a)
bIntervals := flattenHours(b)
// Sort intervals by Start (if not guaranteed sorted)
// You could add sort.Slice here if necessary
// Assuming input data is sorted for now
intersection := intersectIntervals(aIntervals, bIntervals)
return splitIntervalsToDays(intersection)
}
// Example usage
func main() {
// Example inputs for API a and b
a := Hours{
Monday: []OperatingTime{
{Open: ptr(72000)}, // 20:00 Monday open
},
Tuesday: []OperatingTime{
{Close: ptr(3600)}, // 01:00 Tuesday close
{Open: ptr(28800)}, // 08:00 Tuesday open
{Close: ptr(72000)}, // 20:00 Tuesday close
},
}
b := Hours{
Monday: []OperatingTime{
{Open: ptr(64800)}, // 18:00 Monday open
{Close: ptr(82800)}, // 23:00 Monday close
},
Tuesday: []OperatingTime{
{Open: ptr(0)}, // 00:00 Tuesday open
{Close: ptr(3600)}, // 01:00 Tuesday close
{Open: ptr(28800)}, // 08:00 Tuesday open
{Close: ptr(64800)}, // 18:00 Tuesday close
},
}
result := intersectHoursCrossDay(a, b)
// Print result
printHours(result)
}
func printHours(h Hours) {
fmt.Println("Operating hours per day:")
printDay("Monday", h.Monday)
printDay("Tuesday", h.Tuesday)
printDay("Wednesday", h.Wednesday)
printDay("Thursday", h.Thursday)
printDay("Friday", h.Friday)
printDay("Saturday", h.Saturday)
printDay("Sunday", h.Sunday)
}
func printDay(day string, ops []OperatingTime) {
if len(ops) == 0 {
return
}
fmt.Printf("%s:\n", day)
for i := 0; i < len(ops); i += 2 {
open := ops[i].Open
close := ops[i+1].Close
fmt.Printf(" Open: %02d:%02d, Close: %02d:%02d\n", *open/3600, (*open%3600)/60, *close/3600, (*close%3600)/60)
}
}
Output explanation:
The intersection will correctly produce intervals where both a and b are open, including times spanning midnight.
The example shows one interval open Monday 20:00 to Tuesday 01:00 merged properly.
Notes:
You might want to add sorting (e.g., sort.Slice) in flattenHours if your input data isn't strictly sorted.
The code assumes valid data (every open has a close after it).
For more complex rules (like multi-week, or irregular data), you could extend this idea.
To be more robust, handle the case when the last open has no closing in the current week.
If you'd like I can help make this into a full Go module or help with unit tests too. Just tell me!