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

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

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...