Skip to main content

Firebase and Google Chart , timestamp not accurate

This code is to show the temperature on the specific are and record it to the firebase database.

This code is supposedly to record current date into the database then temperature and at last , timestamp, but it instead record a different time (ex. My current data and time is May 1 , 3:11am but it instead recorded April 30 , 6pm) which result onto not showing anything into chart since the chart is set to show only the data on the same day ( if it's may 1 , the chart only shows may 1, data's )

<!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>

i tried tinkering timestamp: firebase.database.ServerValue.TIMESTAMP, , like replacing it with date.now() or any other that should result recording the right time and date , but it didn't fix it .

Via Active questions tagged javascript - Stack Overflow https://ift.tt/JTPrv78

Comments

Popular posts from this blog

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

How to split a rinex file if I need 24 hours data

Trying to divide rinex file using the command gfzrnx but getting this error. While doing that getting this error msg 'gfzrnx' is not recognized as an internal or external command Trying to split rinex file using the command gfzrnx. also install'gfzrnx'. my doubt is I need to run this program in 'gfzrnx' or in 'cmdprompt'. I am expecting a rinex file with 24 hrs or 1 day data.I Have 48 hrs data in RINEX format. Please help me to solve this issue. source https://stackoverflow.com/questions/75385367/how-to-split-a-rinex-file-if-i-need-24-hours-data