Skip to content

Commit

Permalink
Fix day of year calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
zadeviggers committed Oct 6, 2023
1 parent 1e602d9 commit 3b127a4
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 14 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "miniseed",
"version": "0.1.4",
"version": "0.1.5",
"type": "module",
"scripts": {
"build": "vite build",
Expand Down
14 changes: 2 additions & 12 deletions src/miniseed.ts
Original file line number Diff line number Diff line change
@@ -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 },
Expand Down Expand Up @@ -56,20 +57,9 @@ export function serialiseToMiniSEEDBuffer<T extends keyof typeof encodingTypes>(

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(),
Expand Down
21 changes: 21 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -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;
}
2 changes: 1 addition & 1 deletion tests/vaid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ beforeAll(async () => {
});

afterAll(async () => {
// await rm(tempFolder, { recursive: true });
await rm(tempFolder, { recursive: true });
});

describe("Generated data validity", () => {
Expand Down

0 comments on commit 3b127a4

Please sign in to comment.