Using TypeScript to determine the week number - the value on the right side of the math operation must be of data type 'any'

I've spent a lot of time searching for code to help me calculate the week number in my Angular app according to ISO standards. It's been challenging to find JavaScript-specific code, but I believe I may have found something - however, I encountered an error: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

I'm completely stumped by this error message. Below is a sample service that I attempted to use with the code:

import { Injectable } from '@angular/core';

@Injectable()
export class WeekNumberService {

  constructor() { }

 ISO8601_week_no(dt)  {
  var tdt = new Date(dt.valueOf());
  var dayn = (dt.getDay() + 6) % 7;
  tdt.setDate(tdt.getDate() - dayn + 3);
  var firstThursday = tdt.valueOf();
  tdt.setMonth(0, 1);
  if (tdt.getDay() !== 4) 
    {
   tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
     }
  return 1 + Math.ceil((firstThursday - tdt) / 604800000);
  }

}

Note: My main goal is to determine the week number only.

Answer №1

tdt holds a Date object, and firstThursday is treated as a number due to the return value of tdt.valueOf(), which is a number representing the time value in milliseconds since January 1, 1970, UTC.

You should avoid performing arithmetic operations between these two variables:

firstThursday - tdt.

Additionally, your current code does not correctly represent an ISO_8601 week date as you desire, instead returning a Date when it should be a String. For example, inputting the Date Monday, December 29, 2008 should yield the output "2009-W01-1".

To obtain the year and day number of the week, simply use Date methods:

var dayNumber = date.getDay() + 1;
var year = date.getFullYear();

To calculate the week number of the year, refer to the solution in the answer provided in this post.

Finally, concatenate the three values to form the ISO week representation:

String isoWeek = year + "-W-" + weekNumber + "-" + dayNumber;

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

Ways to incorporate useEffect within a function or the other way around

Currently, I am facing an issue with my code. I have a function that handles the onChange event to retrieve the input value. Additionally, I have another function that searches for items in an array based on the value from the input and then renders a comp ...

Looping through a PHP foreach function, assigning a distinct identifier for the select element using getElementById

My goal is to extract the price value, $option_value['price'], from a dropdown menu as a string rather than using .value, which fetches something different. I am working with select menus generated in a foreach() loop. Each dropdown menu contain ...

Http' does not have the 'update' property

I recently implemented Angular 2 Release and utilized 'Http' from '@angular/http' for my project. However, I encountered an error when I invoked the method 'update', which resulted in the following message: "Evidently, th ...

Due to high activity on the main thread, a delay of xxx ms occurred in processing the 'wheel' input event

While using Chrome version: Version 55.0.2883.75 beta (64-bit), along with material-ui (https://github.com/callemall/material-ui) version 0.16.5, and react+react-dom version 15.4.1, an interesting warning message popped up as I scrolled down the page with ...

Utilizing client-side properties in an onClick event within Next.js framework

class homeNotLoggedIn extends React.Component { componentDidMount() { function logout(){ localStorage.clear() location.reload() } } render() { return ( <div> < ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

A step-by-step guide on integrating vuetify-component into codeceptjs

When attempting to write tests using codecept.js, I am facing difficulties accessing the vuetify components. <v-layout> <v-flex xs7> <v-text-field ref="video1min" v-model="video1min" :rules=" ...

Trigger a JavaScript function when a key is pressed down

Hey everyone, I'm trying to figure out how to trigger a JavaScript function when a particular key is pressed. For example, I want the function down() to be executed when the down key is pressed and function left() when the left key is pressed. Is ther ...

button that takes you back to the top of a mobile website

I want to customize the Scroll To Top button so that it only appears once the user begins scrolling down, rather than always being visible even when at the top of the page. Just a heads up, I don't have much experience with JavaScript, so I might need ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

A guide to submitting comments with Angular 2 using a GitHub OAuth token

I'm attempting to utilize a GitHub OAuth Token for posting comments in Angular 2. Below is the code I am using: postComment(token: string, number: Number, body: string): Promise<Comment> { let headers = new Headers() headers.append('Auth ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

Enclose each set of objects, such as text, within a separate div, except for div elements

Is there a way to wrap each immediate group of objects that are not contained in a div with a wrap class? Input: var $code = 'Lorem Ipsum <p>Foo Bar</p> <div class="myclass"></div> <p>Foo Bar</p> <div clas ...

Identify changes in attributes on elements that are updated automatically

On my webpage, I want to have two select boxes that are connected so their values always match. Here's an example: Imagine a page with two selects: <select class="myselector"> <option value='1'>1 <br> < ...

Show an array of arrays using a visual table representation

I am working with an Array of arrays in my data, and they are structured like this : https://i.sstatic.net/3grh6.png Now, I am trying to showcase this array in a table, but all I am getting is a blank page. Here is the HTML code for the table (I have incl ...

The current registry configuration does not provide support for audit requests when running npm audit

I am facing an issue with one of my dependencies that is in the form of "protobufjs": "git+https://github.com/danieldanielecki/protobufjs-angularfire.git#master". I installed it using npm install --save https://github.com/danieldanielecki/protobufjs-angula ...

How can we implement :focus-within styling on Material-UI Select when the input is clicked?

I am currently implementing a Select component inside a div element: <div className="custom-filter custom-filter-data"> <DateRangeIcon className="search-icon"/> <FormControl variant='standard& ...

Having issues passing parameters with Ajax, Python Bottle, Jquery, and JSON collaboration

Every time I make an AJAX request POST, the newUser() function seems to be ignoring any arguments being passed even though I have filled out both userInput and passInput fields. Here's the JS/JQ/AJAX code snippet: var userInput = document ...

Having difficulty deleting a checkbox element using JavaScript

My goal is to have a feature where users can effortlessly add or remove checkbox div elements as needed. The code I have written successfully adds and resets checkboxes, but I am encountering an issue when trying to remove them. I am struggling to identif ...

Building a matrix-esque table using d3.js reminiscent of HTML tables

I would like to generate a table resembling a matrix without numerical values. 1. Here is an example of my database table: | CODE | STIL | SUBSTIL | PRODUS | |------|-------|----------|---------| | R | stil1 | substil1 | produs1 | | R | stil1 | s ...