Home > Software design >  Converting ISO datetime format to readable format in React
Converting ISO datetime format to readable format in React

Time:12-11

I am fetching data from an API in localhost. The date & time I get are in the following format:

"2021-12-08T13:52:16.043"

I just want to remove the time part and show only the date. Something like:

2021-12-08 or 2021/12/08 does not matter.

this is my code in React

{allComments.map(c=> (
    <div>
      <p>{c.time.toLocalDateString()}</p>
    </div>
  )
)}

This is not working. The error says toLocalDateString() is not a function. Thats what I found after some research. Could someone please help me with the write function and how to use it?

CodePudding user response:

You will need to parse your date string into an actual Date object and then call toLocaleDateString.

For formatting options, see: Intl.DateTimeFormat

const c = { time: '2021-12-08T13:52:16.043' };

console.log(new Date(c.time).toLocaleDateString()); // 12/8/2021

Alternatively:

const c = { time: '2021-12-08T13:52:16.043' };

console.log(new Date(c.time).toLocaleString('en-US', {
  year: 'numeric',
  month: 'numeric',
  day: 'numeric'
})); // 12/8/2021


Here is an example in React that uses different date-time formatting for display and element title.

const { useEffect, useMemo, useState } = React;

// Quick and dirty way to has a string for use as a key
const keyHash = (text) => CryptoJS.MD5(text).toString();

const fetchComments = () => Promise.resolve([
  { time: '2021-12-08T13:52:16.043', text: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged." },
  { time: '2021-12-09T13:52:16.043', text: "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." },
]);

const CommentTime = (props) => {
  const { time, locale = 'en-US' } = props;
  
  const display = useMemo(() => (
    new Date(time).toLocaleDateString(locale)
  ), [time]);
  
  const tooltip = useMemo(() => (
    new Date(time).toLocaleString(locale, {
      dateStyle: 'full',
      timeStyle: 'full'
    })
  ), [time]);
  
  return (
    <div className="comment-time" title={tooltip}>{display}</div>
  )
};

const CommentEntry = (props) => {
  const { time, text } = props;
  return (
    <div className="comment-entry">
      <CommentTime time={time} />
      <div className="comment-text">{text}</div>
    </div>
  );
};

const CommentStream = (props) => {
  const { comments } = props;
  return (
    <div className="comment-stream">
      {comments.map(({ text, time }) => (
        <CommentEntry key={keyHash(text)} text={text} time={time} />
      ))}
    </div>
  )
};

const App = ({title}) => {
  const [comments, setComments] = useState([]);

  useEffect(() => fetchComments().then(setComments), []);

  return (
    <div>
      <CommentStream comments={comments} />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('react-app'));
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #222;
  color: #FFF;
}

.comment-stream {
  display: flex;
  flex-direction: column;
  padding: 0 4vw;
  gap: 0.5em;
}

.comment-entry {
  display: flex;
  flex-direction: column;
  padding: 0.5em;
  border: thin solid #000;
  background: #444;
  font-size: 0.9rem;
}

.comment-time {
  font-size: 0.667rem;
  font-style: italic;
  color: #DDD;
}

.comment-text {
  margin-top: 0.25em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/core.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/md5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="react-app"></div>

  • Related