From 3b127a4a1b0cab0dbe8cf11b2190d7a0b8800f3f Mon Sep 17 00:00:00 2001 From: Zade Viggers Date: Fri, 6 Oct 2023 22:55:52 +1300 Subject: [PATCH] Fix day of year calculation --- package.json | 2 +- src/miniseed.ts | 14 ++------------ src/utils.ts | 21 +++++++++++++++++++++ tests/vaid.test.ts | 2 +- 4 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 src/utils.ts diff --git a/package.json b/package.json index e1962ff..4e2b965 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "miniseed", - "version": "0.1.4", + "version": "0.1.5", "type": "module", "scripts": { "build": "vite build", diff --git a/src/miniseed.ts b/src/miniseed.ts index e75f84f..0e02bf0 100644 --- a/src/miniseed.ts +++ b/src/miniseed.ts @@ -1,5 +1,6 @@ import { jDataView } from "z-jdataview-temp-publish"; import { buf as bufToCRC } from "crc-32/crc32c"; +import { getDayOfYear } from "./utils"; const encodingTypes = { text: { code: 0, byteSize: 1 }, @@ -56,20 +57,9 @@ export function serialiseToMiniSEEDBuffer( if (metadata.startTime instanceof Date) { // From https://stackoverflow.com/a/8619946 - const start = new Date(metadata.startTime.getFullYear(), 0, 0); - const diff = - metadata.startTime.valueOf() - - start.valueOf() + - (start.getTimezoneOffset() - - metadata.startTime.getTimezoneOffset()) * - 60 * - 1000; - const oneDay = 1000 * 60 * 60 * 24; - const dayOfYear = Math.floor(diff / oneDay); - metadata.startTime = { year: metadata.startTime.getFullYear(), - dayOfYear, + dayOfYear: getDayOfYear(metadata.startTime), hour: metadata.startTime.getHours(), minute: metadata.startTime.getMinutes(), second: metadata.startTime.getSeconds(), diff --git a/src/utils.ts b/src/utils.ts new file mode 100644 index 0000000..68f2651 --- /dev/null +++ b/src/utils.ts @@ -0,0 +1,21 @@ +/** + * Returns a number 1-366 representing how far through the year the date is. + * Ideally port this to Temporal when it comes out. + * + * Credit to https://stackoverflow.com/a/26426761 + */ +export function getDayOfYear(date: Date): number { + // Get Day of Year + var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + var mn = date.getMonth(); + var dn = date.getDate(); + var dayOfYear = dayCount[mn] + dn; + if (mn > 1 && isLeapYear(date)) dayOfYear++; + return dayOfYear; +} + +function isLeapYear(date: Date): boolean { + const year = date.getFullYear(); + if ((year & 3) != 0) return false; + return year % 100 != 0 || year % 400 == 0; +} diff --git a/tests/vaid.test.ts b/tests/vaid.test.ts index 94cfd49..c2455f0 100644 --- a/tests/vaid.test.ts +++ b/tests/vaid.test.ts @@ -14,7 +14,7 @@ beforeAll(async () => { }); afterAll(async () => { - // await rm(tempFolder, { recursive: true }); + await rm(tempFolder, { recursive: true }); }); describe("Generated data validity", () => {