You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DialogFlow ES时间问候异常:夜间显示Good Morning及Intl.DateTimeFormat报错排查

DialogFlow ES欢迎功能问题排查与解决方案

问题1:夜间运行始终显示Good Morning问候语

原因分析

当前代码用new Date()获取的是服务器默认UTC时区的时间,而非用户本地时区时间。比如用户在UTC-5时区的夜间23点,服务器UTC时间为次日4点,刚好落入hour >=5 && hour <12的判断区间,导致错误显示Good Morning。

解决方案

通过DialogFlow请求对象获取用户时区,基于用户时区计算本地时间:

function welcome(agent) {
    // 获取用户时区(DialogFlow请求中自带该信息)
    const userTimeZone = agent.request.body.queryResult.timeZone;
    // 转换为用户本地时间
    const currentTime = new Date(new Date().toLocaleString('en-US', { timeZone: userTimeZone }));
    const hour = currentTime.getHours(); 

    let greeting = "hello";
    if (hour >= 5 && hour < 12) {
        greeting = "Good morning.";
    } else if (hour >= 12 && hour < 18) {
        greeting = "Good afternoon.";
    } else if (hour >= 18 && hour < 22) {
        greeting = "Good evening.";
    } else {
        greeting = "Good night.";
    }
 
    agent.add(`🎵 ${greeting} my friend? I'm Si Kompang`);
    agent.add("May I know what is your name?");
}
  • 核心逻辑:利用toLocaleString结合用户时区转换时间,确保获取的小时数对应用户本地时段。

问题2:使用Intl.DateTimeFormat出现undefined报错

原因分析

  1. Node.js版本过低:DialogFlow关联的Firebase云函数默认可能使用Node.js 10及以下版本,对Intl.DateTimeFormat的特性支持不全。
  2. API调用错误:若传递的参数格式错误(如时区字符串不合法),也会触发undefined报错。

解决方案

方案1:升级Node.js版本

在Firebase云函数的package.json中指定支持完整Intl API的Node.js版本(推荐16+):

{
  "engines": {
    "node": "16"
  }
}

方案2:正确使用Intl.DateTimeFormat获取本地小时

结合用户时区,规范调用Intl.DateTimeFormat:

function welcome(agent) {
    const userTimeZone = agent.request.body.queryResult.timeZone;
    const currentTime = new Date();
    // 用Intl.DateTimeFormat获取用户本地24小时制小时数
    const hourStr = new Intl.DateTimeFormat('en-US', {
        hour: '2-digit',
        hour12: false,
        timeZone: userTimeZone
    }).format(currentTime);
    // 转换为数字类型用于判断
    const hour = parseInt(hourStr, 10);

    let greeting = "hello";
    if (hour >= 5 && hour < 12) {
        greeting = "Good morning.";
    } else if (hour >= 12 && hour < 18) {
        greeting = "Good afternoon.";
    } else if (hour >= 18 && hour < 22) {
        greeting = "Good evening.";
    } else {
        greeting = "Good night.";
    }
 
    agent.add(`🎵 ${greeting} my friend? I'm Si Kompang`);
    agent.add("May I know what is your name?");
}
  • 注意:format()返回的是字符串,必须转为数字后再进行区间判断。

内容的提问来源于stack exchange,提问作者Ken

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 18:43:28