78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import type { ToolInput } from "../../core/io/input-types";
|
|
import type { ToolResult } from "../../core/io/output-types";
|
|
import type { ToolContext } from "../../core/plugins/plugin-types";
|
|
import type { TimestampOptions } from "./index";
|
|
|
|
export async function runTimestampConverter(
|
|
input: ToolInput,
|
|
options: TimestampOptions,
|
|
context?: ToolContext
|
|
): Promise<ToolResult> {
|
|
void context;
|
|
|
|
const text = (input.text || "").trim();
|
|
if (!text) {
|
|
throw new Error("No input provided.");
|
|
}
|
|
|
|
if (options.mode === "timestamp-to-date") {
|
|
let ts = Number(text);
|
|
if (isNaN(ts)) {
|
|
throw new Error("Invalid timestamp. Enter a numeric Unix timestamp.");
|
|
}
|
|
|
|
if (options.unit === "seconds") {
|
|
ts = ts * 1000;
|
|
}
|
|
|
|
const date = new Date(ts);
|
|
if (isNaN(date.getTime())) {
|
|
throw new Error("Invalid timestamp value.");
|
|
}
|
|
|
|
return {
|
|
type: "json",
|
|
value: {
|
|
input: text,
|
|
iso: date.toISOString(),
|
|
utc: date.toUTCString(),
|
|
local: date.toLocaleString(),
|
|
date: date.toISOString().split("T")[0],
|
|
time: date.toISOString().split("T")[1].replace("Z", ""),
|
|
unixSeconds: Math.floor(date.getTime() / 1000),
|
|
unixMillis: date.getTime(),
|
|
dayOfWeek: date.toLocaleDateString("en-US", { weekday: "long" }),
|
|
},
|
|
};
|
|
} else {
|
|
let date: Date;
|
|
if (/^\d{4}-\d{2}-\d{2}(T|\s)/.test(text)) {
|
|
date = new Date(text);
|
|
} else {
|
|
date = new Date(text);
|
|
}
|
|
|
|
if (isNaN(date.getTime())) {
|
|
throw new Error("Invalid date string. Use ISO 8601 format like 2024-01-15T12:00:00Z.");
|
|
}
|
|
|
|
const unixSeconds = Math.floor(date.getTime() / 1000);
|
|
const unixMillis = date.getTime();
|
|
|
|
return {
|
|
type: "json",
|
|
value: {
|
|
input: text,
|
|
iso: date.toISOString(),
|
|
utc: date.toUTCString(),
|
|
unixSeconds: options.unit === "seconds" ? unixSeconds : undefined,
|
|
unixMillis: options.unit === "milliseconds" ? unixMillis : undefined,
|
|
both: {
|
|
seconds: unixSeconds,
|
|
milliseconds: unixMillis,
|
|
},
|
|
},
|
|
};
|
|
}
|
|
}
|