when using the `<DateFilter>` component (<referenc...
# gooddata-ui
c
when using the
<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:
Copy code
{
  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:
Copy code
{
  from: "2024-01-01 00:00",
  to: "2024-01-30 11:59",
}
m
Hello Cayce, I believe the thread here may shed some light on your inquiry: https://gooddataconnect.slack.com/archives/C01UR5BGAHY/p1685058456454199
c
seems the answer is no, there is no utility function to convert a relative date to an absolute date in the sdk, is that correct? Boris went on to mention something about using the component and only changing a single parameter, but I'm not sure what that is supposed to reference, any insight on that?
I decided to write a quick utility function to handle this conversion when the <DateFilter> selection is a relative type. Note: This uses momentJS since our project is still using it, but could be easily modified for date-fns, dayjs, or even vanilla if you have the time:
Copy code
const 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:
Copy code
if (selectedFilterOption.type.includes("relative")) {
  console.log(
    convertRelativeDateFilterOptionToAbsoluteValues(
      selectedFilterOption as RelativeDateFilterOption,
      excludeCurrentPeriod
    )
  );
}
Feedback welcomed, and I hope this helps somebody else in the future!
🙌 1