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

Firebase与Google Chart时间戳不准确问题求助

Firebase时间戳与本地时间不一致导致Google Chart无数据问题

问题现象

  • 代码用于展示特定区域温度并将数据记录至Firebase数据库,预期记录当前日期、温度及时间戳
  • 实际记录时间与本地时间存在时差(例如:本地时间为5月1日3:11am,数据库记录时间为4月30日6pm)
  • 导致Google Chart因仅展示当日数据而无内容显示
  • 尝试将firebase.database.ServerValue.TIMESTAMP替换为Date.now()后问题仍未解决

原代码

<!DOCTYPE html>
<html>
  <head>
    <title>Temperature Chart</title>
    <!-- Load Google Charts API -->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      google.charts.load('current', {'packages':['line']});
      google.charts.setOnLoadCallback(drawChart);

      function drawChart() {
        // Get the temperature data from the Firebase Realtime Database
        var currentDate = getFormattedDate(new Date());
        var temperatureRef = database.ref('temperature/' + currentDate + '/temperatureData');
        var temperatureRef = firebase.database().ref('temperature');
        temperatureRef.on('value', function(snapshot) {
          var data = new google.visualization.DataTable();
          data.addColumn('datetime', 'Time');
          data.addColumn('number', 'Temperature');

          snapshot.forEach(function(childSnapshot) {
            var childData = childSnapshot.val();
            data.addRow([new Date(childData.timestamp), childData.temperature]);
          });

          var options = {
            chart: {
              title: 'Temperature Chart',
              subtitle: 'Past 24 hours'
            },
            width: 900,
            height: 500
          };

          var chart = new google.charts.Line(document.getElementById('chart_div'));

          chart.draw(data, google.charts.Line.convertOptions(options));
        });
      }
      function getFormattedDate(date) {
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        return year + '-' + month + '-' + day;
      }
    </script>
  </head>
  <body>
    <div id="chart_div"></div>

    <!-- Initialize Firebase -->
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-database.js"></script>
    <script>
      var firebaseConfig = {
        apiKey: ""
        authDomain: ""
        databaseURL:""
        projectId: ""
        storageBucket: ""
        messagingSenderId: ""
        appId: ""
        measurementId: ""
      };
      firebase.initializeApp(firebaseConfig);

      // Get a reference to the Firebase Realtime Database
      var database = firebase.database();

      var openWeatherMapUrl = 'https://api.openweathermap.org/data/2.5/weather?q=Santa+Ana,Ph&appid=cfc8944cfa43267863bf72049929f745&units=metric';
      
      // Update the Firebase Realtime Database with the latest temperature data
      function updateDatabase() {
  // Get the current time and the start of the current day
  var currentTime = new Date();
console.log('Current time:', currentTime);
var startOfDay = new Date(currentTime.getFullYear(), currentTime.getMonth(), currentTime.getDate());

  // Check if the current time is within the current day
    if (currentTime >= startOfDay) {
    // Get the current temperature from OpenWeatherMap API
    fetch(openWeatherMapUrl)
      .then(response => response.json())
      .then(data => {
       // Get the current date in YYYY-MM-DD format
    var currentDate = currentTime.toISOString().slice(0,10);

// Create a new database record with the temperature data for the current day
var temperatureRef = database.ref('temperature/' + currentDate).push();
temperatureRef.set({
  timestamp: firebase.database.ServerValue.TIMESTAMP,
  temperature: data.main.temp
});

// Call the drawChart function with the current day parameter
drawChart(startOfDay);
})
.catch(error => console.error(error));
}
}

      // Call the updateDatabase() function every 3 hours to update the temperature data
      setInterval(updateDatabase, 3 * 60 * 60 * 1000);
    </script>
  </body>
</html>

问题根源

Firebase的ServerValue.TIMESTAMP和Date.now()均为UTC时间戳,但生成存储路径时使用的currentTime.toISOString().slice(0,10)也是基于UTC的日期。当本地时区为UTC+N时,凌晨时段的本地日期会比UTC日期早一天,导致数据被存到前一天的节点中,而图表读取的是本地当日节点,因此无数据显示。

修复方案

1. 统一日期生成逻辑(基于本地时间)

替换updateDatabase中currentDate的生成方式,使用已有的getFormattedDate函数(基于本地时间),确保存储路径与本地日期一致:

// 替换原currentDate生成代码
var currentDate = getFormattedDate(currentTime);

2. 修正图表数据读取逻辑

原代码重复定义temperatureRef并读取整个temperature节点,改为仅读取当日节点:

function drawChart() {
  var currentDate = getFormattedDate(new Date());
  // 仅读取本地当日的温度数据
  var temperatureRef = database.ref('temperature/' + currentDate);
  temperatureRef.on('value', function(snapshot) {
    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Time');
    data.addColumn('number', 'Temperature');

    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
      // UTC时间戳会自动转换为本地时间显示
      data.addRow([new Date(childData.timestamp), childData.temperature]);
    });

    var options = {
      chart: {
        title: '温度图表',
        subtitle: '过去24小时'
      },
      width: 900,
      height: 500
    };

    var chart = new google.charts.Line(document.getElementById('chart_div'));
    chart.draw(data, google.charts.Line.convertOptions(options));
  });
}

3. 移除冗余代码

删除updateDatabase中多余的日期判断if (currentTime >= startOfDay),因为startOfDay是当日0点,currentTime必然满足该条件。

4. 优化函数调用

修改updateDatabase中的drawChart(startOfDay)为drawChart(),因为drawChart不需要参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 03:17:07