Files
api_health/agent/tools/calendar/utils.js
2026-05-30 16:41:26 +08:00

87 lines
2.2 KiB
JavaScript

import * as z from "zod"
import { tool } from "langchain"
import lunar from "lunar-javascript"
const { Solar, Lunar, HolidayUtil, TermUtil } = lunar
/**
* 获取准确时间工具
* 通过国内权威时间源获取当前准确时间
* @returns {string} - 返回当前准确时间的JSON字符串
*/
export async function getAccurateTime() {
const timeSources = [
{
name: 'timeapi.io',
url: 'https://timeapi.io/api/Time/current/zone?timeZone=Asia/Shanghai',
method: 'json'
},
{
name: '国家授时中心',
url: 'http://www.ntsc.ac.cn',
method: 'header'
},
{
name: '阿里云',
url: 'https://www.aliyun.com',
method: 'header'
},
{
name: '腾讯云',
url: 'https://cloud.tencent.com',
method: 'header'
},
{
name: '华为云',
url: 'https://www.huaweicloud.com',
method: 'header'
}
]
for (const source of timeSources) {
try {
const startTime = Date.now()
const res = await fetch(source.url)
const latency = Date.now() - startTime
let timestamp = null
let beijingTime = null
if (source.method === 'json') {
const data = await res.json()
timestamp = new Date(data.dateTime).getTime()
beijingTime = data.dateTime
} else if (source.method === 'header') {
const dateHeader = res.headers.get('Date')
if (dateHeader) {
timestamp = new Date(dateHeader).getTime()
beijingTime = new Date(timestamp).toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' })
}
}
if (timestamp) {
return {
timestamp,
date: new Date(timestamp).toISOString(),
localTime: beijingTime,
source: source.name,
latency: latency,
success: true
}
}
} catch (error) {
console.log(`${source.name} 获取时间失败: ${error.message}`)
continue
}
}
const date = new Date()
return {
timestamp: date.getTime(),
date: date.toISOString(),
localTime: date.toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' }),
success: false,
message: '使用本地时间作为备份'
}
}