1

I have a datetime column in mysql which reads "2021-05-10 08:01:02" but when I pull it from the database it reads "2021-05-10T00:01:02.000Z" instead. my other data is 2021-05-10 10:01:02 but reads as 2021-05-15T02:01:02.000Z and also "2021-04-12 09:10:50" reads as "2021-04-12T01:10:50.000Z"

Full Stats.js frontend code

import React, { useState, useEffect } from "react";
import Navbar from "../Navbar/Navbar";
import Axios from "axios"; //axios library to make requests to api
import "./Stats.css";

function Stats() {
  const [customerList, setCustomerList] = useState([]); //store all that information of the database in a list
  //make an axios request to get information from database
  const getCustomers = () => {
    Axios.get("http://localhost:3001/customers").then((response) => {
      //console.log("successfully retrieved customers list from database");
      console.log(response.data);
      setCustomerList(response.data);
    });
  };

  
    const [currentTime, setCurrentTime] = useState(1);
  {/*}
    useEffect(() => {
      fetch("/time")
        .then((res) => res.json())
        .then((data) => {
          setCurrentTime(data.time);
        });
    }, []);
  

    useEffect(() => {
      fetch("/time")
        .then((res) => res.json())
        .then((data) => {
          const dateStr = new Date(data.time).toLocalDateString('en-CA');
          const timeStr = new Date(data.time).toLocalTimeString();
          const dateTime = `${dateStr} ${timeStr}`;
          setCurrentTime(dateTime);
        });
    }, []);
    */}
    
  return (
    <div>
      <Navbar />
      <div className="container">
      <h1>Dashboard</h1>
      <button onClick={getCustomers}>Show Dashboard</button>
      </div>
      <table className="customertable">
        <thead>
        <tr>
          <th>S/N</th>
          <th>Customer Name</th>
          <th>Customer Email</th>
          <th>Counts of Visit</th>
          <th>Latest Time of Visit</th>
          <th>Contacted?</th>
        </tr>
        </thead>
        <tbody>
        {customerList.map((val, key) => {
          return (
            <tr>
              <td>{val.ID}</td>
              <td>{val.name}</td>
              <td>{val.email}</td>
              <td>{val.counts_of_visit}</td>
              <td>{val.latest_time_of_visit}</td>
              <td>{val.contacted}</td>
            </tr>
          );
        })}
        </tbody>
      </table>
    </div>
  );
}

export default Stats;

Here is my backend .js code for reference

//set up express server
const express = require("express");
const app = express();
//set up sql server
const mysql = require("mysql");
const cors = require("cors");

app.use(cors());
app.use(express.json());
//create a variable called db to make your SQL Statements
const db = mysql.createConnection({
  user: "",
  host: "",
  password: "",
  database: "",
});

//GET REQUEST to database to retrieve customers information from database
app.get("/customers", (req, res) => {
  db.query("SELECT * FROM customer_info", (err, result) => {
    if (err) {
      console.log(err);
    } else {
      {/*}
      const dateStr = new Date(val.latest_time_of_visit).toLocalDateString('en-CA');
      const timeStr = new Date(val.latest_time_of_visit).toLocalTimeString();
      const dateTime = `${dateStr} ${timeStr}`;
    */}
      res.send(result);
    }
  });
});

//check if backend server is running
app.listen(3001, () => {
  console.log("Your server is running on port 3001");
});

fyceheist
  • 11
  • 2
  • 1
    There are a lot of libraries written to solve this problem. Luxon and date-fns are some of the bigger ones. You could also use vanilla's Date object with new Date(data.time), then format it yourself using the date methods. The format that your database is giving you is called iso-8601. It's very compatible with any decent datetime library. – Charles Bamford May 24 '21 at 16:33
  • The question should be in the main part of the post, as it stands there is no question. Formatting dates has been dealt with [many, many times before](https://stackoverflow.com/search?q=%5Bjavascript%5D+how+to+format+a+date). – RobG May 24 '21 at 22:34

1 Answers1

0

Just as @charles-bamford commented, you can use any date library to format your date as you like; date-fns is a famous one for that purpose.

Also, you can manually use the date object in JS to format the date as you like, and Intl.DateTimeFormat could also be helpful. Here is a quick code that might help you using the native Date object methods.

In the use-Effect method:

   useEffect(() => {
      fetch("/time")
        .then((res) => res.json())
        .then((data) => {
          const dateStr = new Date(data.time).toLocalDateString('en-CA');
          const timeStr = new Date(data.time).toLocalTimeString();
          const dateTime = `${dateStr} ${timeStr}`;
          setCurrentTime(dateTime);
        });
    }, []);

In case you want the val.latest_time_of_visit to have the same value as the above currentTime has, you you can use the same code as above, but with the specific respective value just before returning the component.

Like the following:

return (
    <div>
      <Navbar />
      <h1>Statistics:</h1>
      <button onClick={getCustomers}>Show Dashboard</button>
      <table className="customertable">
        <tr>
          <th>S/N</th>
          <th>Customer Name</th>
          <th>Customer Email</th>
          <th>Counts of Visit</th>
          <th>Latest Time of Visit</th>
          <th>Contacted?</th>
        </tr>
        {customerList.map((val, key) => {
          const dateStr = new Date(val.latest_time_of_visit).toLocalDateString('en-CA');
          const timeStr = new Date(val.latest_time_of_visit).toLocalTimeString();
          const dateTime = `${dateStr} ${timeStr}`;

          return (
            <tr>
              <td>{val.ID}</td>
              <td>{val.name}</td>
              <td>{val.email}</td>
              <td>{val.counts_of_visit}</td>
              <td>{dateTime}</td>
              <td>{val.contacted}</td>
            </tr>
          );
        })}
      </table>
    </div>
  );
  • So after i add this code in the Stats.js, when I pull data from mysql it will auto render a correct date time? – fyceheist May 24 '21 at 17:26
  • @fyceheist Yes, it will. You can also take a look at the other libraries and objects I mentioned above. – Abdulrahman Ali May 24 '21 at 17:32
  • Hi I have used the same thing but its still showing the same time and date not changed. You may refer to the code i posted. below. – fyceheist May 24 '21 at 17:40
  • I don't see where you have added the code. if you meant in your original question post that the value you wanna see the date in is `val.latest_time_of_visit`, then you can use the same three lines above but with that exact value, otherwise, please specify the exact problem in the question post & edit it if necessary. – Abdulrahman Ali May 24 '21 at 18:06
  • @fyceheist I edited the answer to include the specific `val.latest_Time_of_visit` table field. See if that helps and solves your problem. And edit your question post instead of posting questions as answers here. – Abdulrahman Ali May 24 '21 at 18:15
  • Hello, I have this errors: TypeError: (intermediate value).toLocalDateString is not a function in (anonymous function) src/components/Stats/Stats.js:54 Stats src/components/Stats/Stats.js:45 ▶ 18 stack frames were collapsed. (anonymous function) src/components/Stats/Stats.js:13 – fyceheist May 25 '21 at 01:48