Skip to content

Commit 26c8c3e

Browse files
authored
fix: time related issues in the "map by line" page (#936)
1 parent 05ff848 commit 26c8c3e

File tree

1 file changed

+39
-9
lines changed

1 file changed

+39
-9
lines changed

src/hooks/useSingleLineData.ts

Lines changed: 39 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,12 @@ export const useSingleLineData = (lineRef?: number, routeIds?: number[]) => {
1313
const [filteredPositions, setFilteredPositions] = useState<Point[]>([])
1414
const [startTime, setStartTime] = useState<string>('00:00:00')
1515
const [plannedRouteStops, setPlannedRouteStops] = useState<BusStop[]>([])
16-
16+
const today = new Date(timestamp)
17+
const tomorrow = new Date(today)
18+
tomorrow.setDate(tomorrow.getDate() + 1)
1719
const { locations, isLoading: locationsAreLoading } = useVehicleLocations({
18-
from: +new Date(timestamp).setHours(0, 0, 0, 0),
19-
to: +new Date(timestamp).setHours(23, 59, 59, 999),
20+
from: +today.setHours(0, 0, 0, 0),
21+
to: +tomorrow.setHours(0, 0, 0, 0),
2022
lineRef,
2123
splitMinutes: 360,
2224
pause: !lineRef,
@@ -35,17 +37,45 @@ export const useSingleLineData = (lineRef?: number, routeIds?: number[]) => {
3537
return pos
3638
}, [locations])
3739

40+
function convertTo24HourAndToNumber(time: string): number {
41+
const match = time.match(/(\d+):(\d+):(\d+)\s(AM|PM)/)
42+
if (!match) return 0
43+
44+
const [, hour, minute, , modifier] = match
45+
let newHour = parseInt(hour, 10)
46+
if (modifier === 'AM' && newHour === 12) newHour = 0
47+
if (modifier === 'PM' && newHour !== 12) newHour += 12
48+
49+
return newHour * 60 + parseInt(minute, 10)
50+
}
51+
3852
const options = useMemo(() => {
39-
const options = positions
40-
.map((position) => position.point?.siri_ride__scheduled_start_time) // get all start times
41-
.filter((time, i, arr) => arr.indexOf(time) === i) // unique
42-
.map((time) => new Date(time ?? 0).toLocaleTimeString()) // convert to strings
53+
const filteredPositions = positions.filter((position) => {
54+
const startTime = position.point?.siri_ride__scheduled_start_time
55+
return !!startTime && +new Date(startTime) > +today.setHours(0, 0, 0, 0)
56+
})
57+
58+
if (filteredPositions.length === 0) return []
59+
60+
const uniqueTimes = Array.from(
61+
new Set(
62+
filteredPositions
63+
.map((position) => position.point?.siri_ride__scheduled_start_time)
64+
.filter((time): time is string => !!time)
65+
.map((time) => time.trim()),
66+
),
67+
)
68+
.map((time) => new Date(time).toLocaleTimeString()) // Convert to 24-hour time string
4369
.map((time) => ({
44-
// convert to options
4570
value: time,
4671
label: time,
4772
}))
48-
return options
73+
74+
const sortedOptions = uniqueTimes.sort(
75+
(a, b) => convertTo24HourAndToNumber(a.value) - convertTo24HourAndToNumber(b.value),
76+
)
77+
78+
return sortedOptions
4979
}, [positions])
5080

5181
useEffect(() => {

0 commit comments

Comments
 (0)