Home > Enterprise >  ReactJS: convert date to a hours/minutes ago or day/hours ago
ReactJS: convert date to a hours/minutes ago or day/hours ago

Time:07-07

someone can help me, i have a date of coment with result:

June 10, 2022, 3:29 PM

i want to convert if the date coment same with the day now, value:

14 hours, 27 minutes ago

when the date coment not same with day now:

2 day, 15 hours ago

CodePudding user response:

Use Moment.js fromNow() this will produce your desired result!

moment([2007, 0, 29]).fromNow();     // 4 years ago
moment([2007, 0, 29]).fromNow(true); // 4 years

CodePudding user response:

Presented below is one possible way to achieve the desired objective.

Code Snippet

const {useState} = React;
const Thingy = ({...props}) => {
  // state-variable to hold the selected date
  // IRL - this info will come from some other source (may be API, etc)
  const [commentDate, setCommentDate] = useState(null);
  // method to display appropriate suffix (day/s, hour/s, minute/s)
  const getWord = (v, type = 'day') => {
    if (v > 0) {
      if (v > 1) return `${v} ${type}s `;
      return `${v} ${type} `;
    }
    return '';
  };
  // method to convert given time-difference to days, hours, minutes
  // Credit: https://stackoverflow.com/a/8528531/13658816
  const dhm = (t) => {
      var cd = 24 * 60 * 60 * 1000,
          ch = 60 * 60 * 1000,
          d = Math.floor(t / cd),
          h = Math.floor( (t - d * cd) / ch),
          m = Math.round( (t - d * cd - h * ch) / 60000),
          pad = function(n){ return n < 10 ? '0'   n : n; };
    if( m === 60 ){
      h  ;
      m = 0;
    }
    if( h === 24 ){
      d  ;
      h = 0;
    }
    let res = `${getWord(d, 'day')}${getWord(h, 'hour')}${getWord(m, 'minute')}`;
    if (res.length > 0) res  = 'ago';
    return res;
  }
  // method to obtain days, hours, minutes when comment-date is present
  const getDiff = () => {
    if (!commentDate) return null;
    return dhm(Math.abs(new Date() - new Date(commentDate)));
  };
  return (
    <div>
      {JSON.stringify()}
      {commentDate && (<div>
        Comment was made: {getDiff()} <hr/>
      </div>)}
      <label>Comment date-time: </label> &nbsp;
      <input
        type="datetime-local"
        value={commentDate}
        onChange={ev => setCommentDate(ev.target.value)}
        max={
          (new Date()).toISOString()
          .split(':').slice(0,2).join(':')
        }
      />      
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <Thingy />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />

Explanation

Inline comments added to the snippet above.

Credit: https://stackoverflow.com/a/8528531/13658816

  • Related