Cayce Collins
01/30/2024, 7:59 PM<DateFilter>
component (reference link), then selecting a relative date such as "this year", the value of the first argument in the callback onApply
might look like this:
{
from: 0,
granularity: "GDC.time.year",
localIdentifier: "THIS_YEAR",
name: "",
to: 0,
type: "relativePreset",
visible: true,
}
... are there any utils available which will convert this relative date to a formatted date which could provide something similar to:
{
from: "2024-01-01 00:00",
to: "2024-01-30 11:59",
}
Moises Morales
01/30/2024, 10:45 PMCayce Collins
01/30/2024, 11:15 PMCayce Collins
01/31/2024, 5:21 AMconst convertRelativeDateFilterOptionToAbsoluteValues = (
dateFilter: RelativeDateFilterOption,
excludeCurrentPeriod: boolean
) => {
const granularity = dateFilter?.granularity;
if (!granularity) return;
let rawUnitOfTime = granularity?.split(".")?.slice(-1)?.[0];
if (!rawUnitOfTime) return;
const unitOfTime =
rawUnitOfTime === "date"
? "day"
: (rawUnitOfTime?.replace("_us", "") as unitOfTime.Base);
if (!unitOfTime) return;
const dateFormat = "yyyy-MM-DD hh:mm";
const fromDate = dateFilter?.from || 0;
const formattedFromDate = moment()
.add(fromDate, unitOfTime)
.startOf(unitOfTime)
.format(dateFormat);
const toDate = <http://dateFilter.to|dateFilter.to> || 0;
const formattedToDate = moment()
.add(excludeCurrentPeriod ? toDate - 1 : toDate, unitOfTime)
.endOf(unitOfTime)
.format(dateFormat);
return {
from: formattedFromDate,
to: formattedToDate,
};
};
Example usage:
if (selectedFilterOption.type.includes("relative")) {
console.log(
convertRelativeDateFilterOptionToAbsoluteValues(
selectedFilterOption as RelativeDateFilterOption,
excludeCurrentPeriod
)
);
}
Feedback welcomed, and I hope this helps somebody else in the future!