如何从 React Native 中的自定义日期和时间 "from now" 获取周/天/小时/分钟前?

How to get weeks/ days/ hours/ minutes ago from custom date & time "from now" in React Native?

我有一个日期和时间格式:2019-11-25 09:49:19。我们如何与当前日期和时间进行比较并显示为:3 days agoweeks/ hours/ min ago

您可以使用 moment.js 库。 moment.js

moment("20111031", "YYYYMMDD").fromNow(); // 8 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 7 years ago
moment().startOf('day').fromNow();        // 16 hours ago
moment().endOf('day').fromNow();          // in 8 hours
moment().startOf('hour').fromNow();       // an hour ago

您可以使用 npm 中的 npm i moment 包并使用 diff 函数,如下所示: moment.duration(nowMoment.diff(updateMoment)).as("hours")

差异可以按天、小时或分钟来计算。

目前您可以使用 moment 解决您的问题。但是我也提供了一些 VainillaJS 的代码来解决你的问题。

const DAYS_OF_WEEK = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const MONTHS_OF_YEAR = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];

const daysBetween = (date1, date2) => {
  const ONE_DAY_ON_SECONDS = 1000 * 60 * 60 * 24;
  const date1Ms = date1.getTime();
  const date2Ms = date2.getTime();

  const differenceMs = date2Ms - date1Ms;
  return Math.round(differenceMs / ONE_DAY_ON_SECONDS); 
}

const getHoursFromDate = (date) => {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0' + minutes : minutes;
  return hours + ':' + minutes + ' ' + ampm;
}

const dateFromNow = (date) => {
  const currentDate = new Date();

  if(date.getUTCDate() === currentDate.getUTCDate() && date.getUTCMonth() === currentDate.getUTCMonth() && date.getUTCFullYear() === currentDate.getUTCFullYear()) {
    const hours = Math.floor(Math.abs(date - currentDate) / 36e5);

    if (hours === 0) {
      const minutes = Math.round(((Math.abs(date - currentDate) % 86400000) % 3600000) / 60000);
      return minutes <= 1 ? 'A while ago' : `${minutes} minutes ago.`
    } else {
      return `${Math.floor(hours)} hours ago`;
    }
  } else {
    if (date.getUTCFullYear() < currentDate.getUTCFullYear() || daysBetween(date, currentDate) > 6) {
      return `${date.getDate()}/${MONTHS_OF_YEAR[date.getMonth()]} /${date.getFullYear()}`;
    } else {
      return `${DAYS_OF_WEEK[date.getDay()]} at ${getHoursFromDate(date)}`;
    }
  }
}

https://momentjs.com/docs/#/get-set/day/

  • 如果超出范围,则会冒泡至其他周。
moment().day(-7); // last Sunday (0 - 7)
moment().day(0); // this Sunday (0)
moment().day(7); // next Sunday (0 + 7)
moment().day(10); // next Wednesday (3 + 7)
moment().day(24); // 3 Wednesdays from now (3 + 7 + 7 + 7)
  • 根据区域获取或设置星期几。

如果语言环境将星期一指定为一周的第一天,则 moment().weekday(0) 将为星期一。如果周日是一周的第一天,moment().weekday(0) 就是周日。

与moment#day一样,如果超出范围,它将冒泡到其他周。

// when Monday is the first day of the week
moment().weekday(-7); // last Monday
moment().weekday(7); // next Monday
// when Sunday is the first day of the week
moment().weekday(-7); // last Sunday
moment().weekday(7); // next Sunday

经过多次尝试,我找到了确切的解决方案:

moment.utc("2019-12-04 12:00:24").local().startOf('seconds').fromNow()

输出:

30 分钟前、1 小时前、2 周前

这是我在 app.Don 中使用的函数,不需要任何库

export const findDaysDiffrent = (fromDate) => {

let CreatedDate = new Date(fromDate)
let today = new Date()
let requiredDiffrentDays

const oneDay = 24 * 60 * 60 * 1000;
const diffDays = Math.round(Math.abs((CreatedDate - today) / oneDay));

if (diffDays >= 360) {
    requiredDiffrentDays = Math.floor(diffDays / 360) == 1 ? `${Math.floor(diffDays / 365)} year ago` : `${Math.floor(diffDays / 365)} years ago`
} else if (diffDays >= 30) {
    requiredDiffrentDays = Math.floor(diffDays / 30) == 1 ? `${Math.floor(diffDays / 30)} month ago` : `${Math.floor(diffDays / 30)} months ago`
} else if (diffDays < 30) {
    requiredDiffrentDays = (diffDays == 1 || diffDays == 0) ? `${diffDays} day ago` : `${diffDays} days ago`
}

return requiredDiffrentDays;

}

安装 moment 模块

npm install moment

然后,您可以使用以下代码找到时间之前(将要转换的时间替换为created_at)。

import moment from 'moment';
const dateTimeAgo = moment(new Date(created_at)).fromNow();