import type { CurrentTimeResult, TimeInZoneParams, TimeInZoneResult } from './types.js';
import { logger } from '../utils/logger.js';
/**
* 获取当前 UTC 时间
* @returns 包含 ISO 8601 格式时间和 Unix 时间戳的对象
*/
export function getCurrentTime(): CurrentTimeResult {
logger.debug('Getting current UTC time');
const now = new Date();
const iso = now.toISOString();
const unix = now.getTime();
const result = {
timestamp: iso,
iso: iso,
unix: unix,
};
logger.debug('Current time retrieved', { result });
return result;
}
/**
* 获取指定时区的当前时间
* @param params 时区参数
* @returns 包含时区时间的对象
*/
export function getTimeInZone(params: TimeInZoneParams): TimeInZoneResult {
const { timezone } = params;
logger.debug('Getting time in zone', { timezone });
try {
// 验证时区是否有效
const formatter = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
});
// 测试时区是否有效
formatter.format(new Date());
logger.debug('Timezone validated successfully', { timezone });
// 获取指定时区的当前时间
const now = new Date();
const formatterWithTz = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
fractionalSecondDigits: 3,
hour12: false,
timeZoneName: 'longOffset',
});
const parts = formatterWithTz.formatToParts(now);
const year = parts.find((p) => p.type === 'year')?.value || '';
const month = parts.find((p) => p.type === 'month')?.value || '';
const day = parts.find((p) => p.type === 'day')?.value || '';
const hour = parts.find((p) => p.type === 'hour')?.value || '';
const minute = parts.find((p) => p.type === 'minute')?.value || '';
const second = parts.find((p) => p.type === 'second')?.value || '';
const fractionalSecond = parts.find((p) => p.type === 'fractionalSecond')?.value || '';
const timeZoneName = parts.find((p) => p.type === 'timeZoneName')?.value || '';
// 构建 ISO 8601 格式的时间字符串
const timestamp = `${year}-${month}-${day}T${hour}:${minute}:${second}.${fractionalSecond}${timeZoneName}`;
const result = {
timestamp,
timezone,
iso: timestamp,
};
logger.debug('Time in zone retrieved successfully', { result });
return result;
} catch (error) {
logger.error(`Invalid timezone: ${timezone}`, error);
throw new Error(`Invalid timezone: ${timezone}. ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}