You need to enable JavaScript to run this app. Firebase Functions显示服务器时间 无法获取用户所在国时区时间如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Firebase Functions显示服务器时间 无法获取用户所在国时区时间如何解决

问题原因
  • 你将new Date()实例化代码写在了云函数触发器外部,Firebase Functions运行时会复用函数实例,只有冷启动时会执行一次外部初始化代码,后续触发触发器时tarih变量一直是首次初始化的旧时间,不会随触发器触发更新
  • JavaScript原生Date对象的getFullYear()/getMonth()/getDate()/getHours()方法默认返回运行环境所在时区的时间值,Firebase Functions的运行环境默认时区为UTC,自然取不到你目标国家的时区时间
解决方案

你可以直接用原生Intl.DateTimeFormatAPI指定目标时区来获取对应时间,不需要引入额外第三方依赖,同时将日期实例化逻辑移到触发器内部,保证每次触发都取最新时间。以下为修正后代码,你只需要替换TARGET_TIME_ZONE为你所需的IANA时区标识符即可(比如中国时区为Asia/Shanghai,土耳其时区为Europe/Istanbul):

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const database = admin.database();
// 替换为你需要的目标时区IANA标识符
const TARGET_TIME_ZONE = 'Europe/Istanbul';

exports.pushNotification = functions.database.ref('Kullanicilar/{userId}/sistemdurumu')
.onWrite((Change, Context) =>{
    const oldDeger = Change.before.val();
    const newDeger = Change.after.val();
    
    if (newDeger > oldDeger){
        // 每次触发触发器都实例化最新的时间对象
        const now = new Date();
        // 按目标时区格式化时间
        const formatter = new Intl.DateTimeFormat('en-US', {
            timeZone: TARGET_TIME_ZONE,
            year: 'numeric',
            month: 'numeric',
            day: 'numeric',
            hour: 'numeric',
            hour12: false
        });
        const timeParts = formatter.formatToParts(now);
        const year = timeParts.find(item => item.type === 'year').value;
        const month = timeParts.find(item => item.type === 'month').value;
        const day = timeParts.find(item => item.type === 'day').value;
        const hour = timeParts.find(item => item.type === 'hour').value;

        database.ref(`Kullanicilar/${Context.params.userId}/sistemdurumu1`).set(Number(year));
        database.ref(`Kullanicilar/${Context.params.userId}/sistemdurumu2`).set(Number(month));
        database.ref(`Kullanicilar/${Context.params.userId}/sistemdurumu3`).set(Number(day)); 
        database.ref(`Kullanicilar/${Context.params.userId}/sistemdurumu4`).set(Number(hour));  
    }
   
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 04:54:03