Is there a way to retrieve the date of the most recent occurrence of a specific "day" in TypeScript?

Looking to retrieve the date (in YYYY-MM-DD format) for the most recent "Wednesday", "Saturday", or any user-specified day. This date could be from either this week or last week, with the most recent occurrence of that particular day. For instance, if today is January 26th, a Thursday, then the date for last Wednesday would be 2023-01-25, previous Thursday would be 2023-01-19, and last Saturday would be 2023-01-21.

I have explored the use of date-fns, which includes the startOfWeek method. However, I encountered an issue with the add function not accepting negative numbers, preventing me from adding -2, -3, etc. As I am new to TypeScript, any assistance or guidance would be greatly appreciated.

Answer №1

This code snippet focuses on JavaScript rather than TypeScript. Take a look:

function getLastGivenDay(day: string): string {
  const today = new Date();
  const todayDay = today.getDay();
  const dayIndex = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"].indexOf(day);

  let lastGivenDay = new Date();
  lastGivenDay.setDate(today.getDate() - (todayDay - dayIndex) % 7);

  if (todayDay < dayIndex || todayDay === dayIndex) {
    lastGivenDay.setDate(lastGivenDay.getDate() - 7);
  }

  return lastGivenDay.toISOString().slice(0, 10);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to implement a dynamic tag using TypeScript in React?

How can I implement dynamic tag typing in React using TypeScript? Take a look at the following code snippet: interface CompProps { tag: string; } const MyComponent: React.FunctionComponent<CompProps> = ({ tag = "div", children }) => { co ...

Exploring the integration of the mongodb-stitch library within an Angular 4 application

I have been experimenting with the MongoDB Stitch service in Angular, and so far I have successfully implemented the service. However, the only way I have managed to connect to the service is by adding the js library hosted on AWS directly into the html pa ...

How can this be happening? It's expected that items will be printed, but for some reason

I'm struggling to figure out why the console.logs aren't showing up. import { GenericRepository, getGenericRepository } from '../src/database/repository/GenericRepository'; import { start, stop } from '../src/index'; import r ...

The Angular7 counterpart of the C# attribute decorator

I'm working with an API method that has an Authorize attribute to verify permissions. [Authorize(ReadIndexes)] public async Task<IActionResult> GetIndexes () { ... } Is there a similar way in Angular to implement permission checks so the API ...

Angular - The 'options' property is not found in the 'HTMLOptionElement' type

Currently, I am attempting to modify the choices in a dropdown menu based on the selection made from another dropdown. This problem led me to come across a helpful resource on a website called "Form Select Change Dynamic List Option Elements Tutorial". How ...

Angular 8 Refresh Token Implementation

I am currently working on an Angular 8 app that is integrated with .NET Core. My goal is to find a way to refresh a JWT token within the application. Within the integration, users are able to validate and receive a token which expires after 30 minutes. T ...

Ways to access the types of function parameters

Obtaining a method's parameter types using ReflectAPI is simple: Reflect.getMetadata('design:paramtypes', target, propertyKey); However, the challenge arises when trying to retrieve a function's parameter types as it constantly return ...

What is the proper way to include type annotation in a destructured object literal when using the rest operator?

When working with objects, I utilize the spread/rest operator to destructure an object literal. Is there a way to add type annotation specifically to the rest part? I attempted to accomplish this task, but encountered an error when running tsc. const { ...

Vue version 3 is encountering an issue with a module that does not have an exported member in the specified path of "../../node_modules/vue/dist/vue"

After I updated my npm packages, errors started popping up in some of the imports from the 'vue' module: TS2305: Module '"../../node_modules/vue/dist/vue"' has no exported member 'X' The X instances affected inclu ...

The error message "Property 'value' is not present on type 'EventTarget & HTMLSelectElement'" indicates that the 'value' property is not recognized on the Event

Here is the code snippet that I am working with: interface IHandleSelection { (value: string): any | void; } interface IPipeChangeEventValueToFunction { (handler: IHandleSelection): (event: React.ChangeEvent<HTMLSelectElement>) => void; ...

Angular - Set value only if property is present

Check if the 'rowData' property exists and assign a value. Can we approach it like this? if(this.tableObj.hasOwnProperty('rowData')) { this.tableObj.rowData = this.defVal.rowData; } I encountered an error when attempting this, specif ...

Instead of using colons, display the separation of hours, minutes, and seconds with underscores

Currently, I am utilizing moment.js to retrieve the present date and time with the intention of formatting it in the specific format below 'MMMM Do YYYY, h:mm:ss a' Unfortunately, the problem arises as the delineation between hours, minutes, and ...

Dynamically determine the data type of a value by analyzing the key property within a function

I have created a custom hook that extends the functionality of the useStata function by accepting key and value props; import { Dispatch, SetStateAction, useCallback, useState } from 'react'; export type HandleModelChangeFn<T> = (key: keyo ...

It appears that the functions in linqts are not clearly defined

Currently, I am in the process of learning Angular4 and facing challenges with getting linqts to function properly. Within my room-list.component.ts file, I include it in this manner: import { List } from 'linqts'; A few lines below, I have my ...

Creating a responsive class getter with Vue.js 3 using the Composition API: a guide

How can I set up a class instance property to reactively display an error message when authentication fails? UserModel.ts export class User { private error: string; set errorMessage(errorMessage: string) { this.error = errorMessage; } get err ...

Disable the loader for a specific method that was implemented in the Interceptor

Custom Loader Interceptor A loader has been implemented within an Interceptor. I have a specific requirement where the loader should not be triggered during the upload() function. It should not be applied to that particular method only. ...

Guide on transforming JSON data into a collection of custom objects using TypeScript

When working with raw data in TypeScript (originally a JSON file and imported using import * as raw_data from './json_file.json'): let raw_data: object = {"a": {"name": "Name a", "desc": "Description a ...

Does Angular 2/4 actually distinguish between cases?

I have a question about Angular and its case sensitivity. I encountered an issue with my code recently where using ngfor instead of ngFor caused it to not work properly. After fixing this, everything functioned as expected. Another discrepancy I noticed w ...

TS1057: It is required that an async function or method has a return type that can be awaited

There was a recent Github issue reported on March 28th regarding async arrow functions generating faulty code when targeting ES5, resulting in the error message: TS1057: An async function or method must have a valid awaitable return type You can find t ...

What is the process for utilizing ts-node ESM in conjunction with node modules?

Disclaimer: I understand that the question below pertains to an experimental feature. I have initiated a thread on the ts-node discussion forum. Nonetheless, I believe that posting on StackOverflow will garner more visibility and potentially result in a qu ...