summaryrefslogtreecommitdiff
path: root/std/datetime/mod.ts
diff options
context:
space:
mode:
authorJacob Gee-Clarke <jacob@jacobgc.me>2020-07-09 20:50:42 +0100
committerGitHub <noreply@github.com>2020-07-09 15:50:42 -0400
commit634d6af7a1506bb209f972ac75af375d0e523d48 (patch)
tree5f58d0db66c44946e45964de2d0a222a77b7963a /std/datetime/mod.ts
parentedb7a0eead3604316b3cca2ac9122c5599445a63 (diff)
feat(std/datetime): Added weekOfYear (#6659)
Diffstat (limited to 'std/datetime/mod.ts')
-rw-r--r--std/datetime/mod.ts24
1 files changed, 24 insertions, 0 deletions
diff --git a/std/datetime/mod.ts b/std/datetime/mod.ts
index 99332e046..426464564 100644
--- a/std/datetime/mod.ts
+++ b/std/datetime/mod.ts
@@ -111,6 +111,30 @@ export function dayOfYear(date: Date): number {
}
/**
+ * Get number of the week in the year (ISO-8601)
+ * @return Number of the week in year
+ */
+export function weekOfYear(date: Date): number {
+ const workingDate = new Date(
+ Date.UTC(date.getFullYear(), date.getMonth(), date.getDate())
+ );
+
+ // Set to nearest Thursday: current date + 4 - current day number
+ // Make Sunday's day number 7
+ workingDate.setUTCDate(
+ workingDate.getUTCDate() + 4 - (workingDate.getUTCDay() || 7)
+ );
+
+ // Get first day of year
+ const yearStart = new Date(Date.UTC(workingDate.getUTCFullYear(), 0, 1));
+
+ // return the calculated full weeks to nearest Thursday
+ return Math.ceil(
+ ((workingDate.valueOf() - yearStart.valueOf()) / 86400000 + 1) / 7
+ );
+}
+
+/**
* Get number of current day in year
* @return Number of current day in year
*/