Home > Software design >  React-Typescript: I don't find the problem why my getCurrentTime Function won't work
React-Typescript: I don't find the problem why my getCurrentTime Function won't work

Time:04-30

I am trying to write a function to display the difference time between current time and e.g. the creation time of a message. Herefore I wrote a function to get my current time before heading to the next step.

I intend to put the result into a table by <td>{getCurrentTime}</td>, but I cannot see any results of this function being displayed. There is not even a second column showing up.

import React from "react";

export function getCurrentTime () {
    let today = new Date();
    let dateTime = (today.getHours() < 10 ? '0' : '')   ':'   (today.getMinutes() < 10 ? '0' : '')   ':'   (today.getSeconds() < 10 ? '0' : '');
    return dateTime;
}

//console.log(getCurrentTime);

export default getCurrentTime

this is where I want the time to be displayed:

const CommitMsgTable = ({ apiCommitsResponse }: CommitMsgTableProps) => {
let colorToggle = false;
return <div><table>{apiCommitsResponse.map(commit => {
    colorToggle = !colorToggle;
    return (
        <tr>
            <td>{getCurrentTime}</td>
            <td style={{ backgroundColor: colorToggle ? "lightgrey" : "white" }}>                
                {commit}
            </td>
        </tr>)
})}
</table></div>

solved by tanmay and El Pandario! I forgot the brackets () after calling {getCurrentTime} in the table data

CodePudding user response:

Something like this should work:

export default function App() {
  return (
    <div className="App">
      <tr>
        <td>Time: {getCurrentTime()}</td>
      </tr>
    </div>
  );
}

export function getCurrentTime () {
  let today = new Date();
  let dateTime = (today.getHours() < 10 ? `0${today.getHours()}` : `${today.getHours()}`)   ':'   (today.getMinutes() < 10 ? `0${today.getMinutes()}` : `${today.getMinutes()}`)   ':'   (today.getSeconds() < 10 ? `0${today.getSeconds()}` : `${today.getSeconds()}`);
  console.log(dateTime);
  return dateTime;
}

CodePudding user response:

I did not understand what you meant, but I think you wanted something like that:

const getCurrentTime = () => {
    const date = new Date();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    const seconds = date.getSeconds();
    const timeString = `${hours.toString().length === 1 ? `0${hours}` : hours}:${minutes.toString().length === 1 ? `0${minutes}` : minutes}:${seconds.toString().length === 1 ? `0${seconds}` : seconds}`;
    return timeString;
};

console.log(getCurrentTime())

  • Related