1

I have been looking around allot for code to use in my program that will calculate the week number (according to ISO standards) in my Angular app using typescript. It is very hard to find a piece of code just in JavaScript, but I think I may have found something- problem is I get an error: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

I have NO idea what this means. Here is a service that I have tried to write to use 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);
  }

}

PS: I am in the end only looking for the week number.

Alfa Bravo
  • 1,961
  • 2
  • 25
  • 45

1 Answers1

1

tdt is a Date and firstThursday is infered as a number because tdt.valueOf() returns a number representing the stored time value in milliseconds since midnight, January 1, 1970 UTC.

You cannot use an arithmetic operations between these two variables :

firstThursday - tdt.

Anyway, your actual code is not designed to return a representation of an ISO_8601 week date as you specified here. You return a Date while you should return a String.
For example, this input Date Monday 29 December 2008 should return this String : "2009-W01-1".

Getting the year and the day number of the week is straight as Date provides methods for :

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

About the week number of the year, you have to implement this.
I invite you to rely on the code in the accepted answer of this post.

Then, just concatenate the three values :

String isoWeek = year + "-W-" + weekNumber + "-" + dayNumber;
davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 1
    I will watch your interventions the next days :) Oh... Relativise : Your Mac Pro Book will have a little delay but enjoy, as Mac, you are today a legend :) – davidxxx Sep 07 '17 at 10:10
  • I have decided to (just for now) remove this as the right answer, due to the fact the post you have referred to uses the following line: var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7); Here "d" is also a date, yet it is used in an arithmetic operation, which no surprise if I use that code: gives me the exact same error... any further help would be appreciated. – Alfa Bravo Sep 12 '17 at 07:40
  • Ok, I marked it correct again because I see that you did give the right answer, without actually specifically pointing it out. Maybe you can just change your answer for future reference to say that all I need to do was to use "tdt.valueOf()" in the "return" line, instead of just tdt. Thanks again. – Alfa Bravo Sep 12 '17 at 07:50