Typescript Function for Dates

I am trying to write functions in typescript to use to back variables in Workshop for specific dates. So i can for example show a metric card that filters data to a specific week or month.

How would i create functions that would return the following? Would need a separate function for each so i can use the dates independently. Dates would be derived from today’s date, not from an object property.

  • Start Date of Prior Week (Sunday)
  • End Date of Prior Week (Monday)
  • Start Date of Prior Month
  • End Date of Prior Month

I did a function more or less similar to your need not a long ago:

@Function() 
    public startEndDateFromDate(date: LocalDate, isStart: boolean = true, isNext: boolean = false, bucketing: string ): LocalDate {
        if ((bucketing !== "Month") && (bucketing !== "Year")) {
            throw new UserFacingError("Your input in the bucketing part must be from the following list: [Month, Year].");
        }
        if(date === undefined) { throw new UserFacingError("No date given, calculation can't be computed") }
        if (bucketing === 'Month') { 
            return (isStart === true) && (isNext === false) ? LocalDate.of(date.getYear(), date.getMonth(), 1) //first Day of current Month
                 : (isStart === true) && (isNext === true) ? LocalDate.of(date.getYear(), date.plusMonths(1).getMonth(), 1) //First Day of next Month 
                 : (isStart === false) && (isNext === false) ? LocalDate.of(date.getYear(), date.plusMonths(1).getMonth(), 1).minusDays(1) //Last Day of current Month
                 : (isStart === false) && (isNext === true) ? LocalDate.of(date.getYear(), date.plusMonths(2).getMonth(), 1).minusDays(1) //Last Day of next Month
                 : LocalDate.now();
        }else if (bucketing === 'Year') { 
            return (isStart === true) && (isNext === false) ? LocalDate.of(date.getYear(), 1, 1) //first Day of current Year
                 : (isStart === true) && (isNext === true) ? LocalDate.of(date.plusMonths(12).getYear(), 1, 1) //First Day of next Year 
                 : (isStart === false) && (isNext === false) ? LocalDate.of(date.getYear(), 12, 31) //Last Day of current Year
                 : (isStart === false) && (isNext === true) ? LocalDate.of(date.plusMonths(12).getYear(), 12, 31) //Last Day of next Year
                 : LocalDate.now(); 
        }else { return LocalDate.now(); }
    }

You can adapt that and replace some of the parameter to fit your need
Hopes this helps you

This is super helpful, thank you. I should be able to adapt for what i need. Thanks again!

1 Like

An alternative option from TypeScript is to use an arbitrary Jan 1st date (1/1/1900) and an arbitrary Sunday date (1/7/1900):

1 Like