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.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.