convert date to now, 12m, 1h, 1d, 1w, 1m, 1y in javascript

To convert a date into a difference from the current time, we can use the Moment.js library. First, install it using npm:

npm install moment
19 chars
2 lines

Then, in your Javascript code, you can use the following code to get the difference in time between the date and the current time, and format it as "now", "12m", "1h", "1d", "1w", "1m", or "1y".

index.tsx
const moment = require('moment');

function formatDate(date) {
  // get the difference in seconds between the date and now
  const diff = moment().diff(date, 'seconds');

  if (diff < 60) {
    return 'now';
  } else if (diff < 3600) {
    return moment.duration(diff, 'seconds').minutes() + 'm';
  } else if (diff < 86400) {
    return moment.duration(diff, 'seconds').hours() + 'h';
  } else if (diff < 604800) {
    return moment.duration(diff, 'seconds').days() + 'd';
  } else if (diff < 2419200) {
    return moment.duration(diff, 'seconds').weeks() + 'w';
  } else if (diff < 29030400) {
    return moment.duration(diff, 'seconds').months() + 'm';
  } else {
    return moment.duration(diff, 'seconds').years() + 'y';
  }
}

const date = new Date('2021-08-24T12:00:00Z');
console.log(formatDate(date)); // output: now (if run within a minute), 1h, 9d, etc.
864 chars
26 lines

The formatDate function takes a Date object as its argument, and uses the moment library to calculate the difference in seconds between the date and the current time. The if-else statements then check the range of the difference in seconds and return the appropriate string based on the criteria specified in the question.

Note that this code assumes that the date passed in is in UTC format. If it is in a different timezone, you may need to adjust the calculation accordingly.

gistlibby LogSnag