Last active
August 9, 2024 18:02
-
-
Save eoguvo/195a4510a37fa2703c1ae43b233fd81a to your computer and use it in GitHub Desktop.
transform preset date ranges (the morning of yesterday) into timestamp dates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { subDays, format, parse, startOfWeek, addWeeks, startOfMonth, subMonths, subWeeks, addMonths, addDays } from "date-fns"; | |
import { ReportFields } from "../WindowDeviceReport.asset"; | |
const getDateRangeFromPresets = function ({ range, timeRange, startTime: customStartTime, endTime: customEndTime, customRange }: ReportFields) { | |
const rangeToOffset = { | |
today: [new Date(), new Date()], | |
yesterday: [subDays(new Date(), 1), subDays(new Date(), 1)], | |
two_days_ago: [subDays(new Date(), 2), subDays(new Date(), 2)], | |
three_days_ago: [subDays(new Date(), 3), subDays(new Date(), 3)], | |
week: [startOfWeek(new Date(), { weekStartsOn: 1 }), startOfWeek(addWeeks(new Date(), 1), { weekStartsOn: 1 })], | |
week_ago: [startOfWeek(subWeeks(new Date(), 1), { weekStartsOn: 1 }), startOfWeek(new Date())], | |
month: [startOfMonth(new Date()), startOfMonth(addMonths(new Date(), 1))], | |
month_ago: [startOfMonth(subMonths(new Date(), 1)), startOfMonth(new Date())] | |
} as Record<string, [Date, Date]>; | |
const timeRangeToOffset = { | |
full_day: ["00:00", "23:59"], | |
morning: ["06:00", "12:00"], | |
afternoon: ["12:00", "18:00"], | |
night: ["18:00", "06:00"], | |
} as Record<string, [string, string]>; | |
let [startDate, endDate] = rangeToOffset[range] || []; | |
let [startTime, endTime] = timeRangeToOffset[timeRange] || []; | |
if (range === "custom") { | |
startDate = new Date(customRange.start); | |
endDate = new Date(customRange.end); | |
} | |
if (timeRange === "custom") { | |
startTime = customStartTime; | |
endTime = customEndTime; | |
} | |
const formattedStartDate = format(startDate, "yyyy-MM-dd"); | |
const formattedEndDate = format(endDate, "yyyy-MM-dd"); | |
const start = parse(`${formattedStartDate} ${startTime}`, "yyyy-MM-dd HH:mm", new Date()).getTime(); | |
let end = parse(`${formattedEndDate} ${endTime}`, "yyyy-MM-dd HH:mm", new Date()).getTime(); | |
if (end <= start) { | |
const gapEnd = format(addDays(start, 1), "yyyy-MM-dd"); | |
end = parse(`${gapEnd} ${endTime}`, "yyyy-MM-dd HH:mm", new Date()).getTime(); | |
} | |
return { start, end }; | |
}; | |
export default getDateRangeFromPresets; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment