如何在React Native中从自定义日期和时间“从现在开始”获取周/天/小时/分钟前?

vngu2lb8  于 2023-06-06  发布在  React
关注(0)|答案(9)|浏览(130)

我有一个日期和时间格式:2019-11-25 09:49:19 .我们如何从当前日期和时间比较这个,可以显示如下:3 days agoweeks/ hours/ min ago

qco9c6ql

qco9c6ql1#

经过多次尝试和尝试,我找到了确切的解决方案:
moment.utc("2019-12-04 12:00:24").local().startOf('seconds').fromNow()
输出如下:
30分钟前
1小时前
2周前

ztmd8pv5

ztmd8pv52#

安装力矩模块

npm install moment

然后,您可以使用以下代码查找time ago(用created_at替换要转换的时间)。

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

7rtdyuoh3#

你可以使用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
6psbrbz9

6psbrbz94#

目前,您可以使用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)}`;
    }
  }
}
qyuhtwio

qyuhtwio5#

截至2022年,Moment是一个遗留项目,现在处于维护模式。你可以使用dayjs。它是moment的直接替代品。

npm install dayjs

然后

import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import localeEn from "dayjs/locale/en"; // With a custom alias for the locale object


 const daysago = (postDate) => { 
        dayjs.extend(relativeTime).locale(localeBn) 
        var fromNowOn = dayjs(postDate).fromNow(); 
        return(fromNowOn)
     };

{daysago("2022-11-07T09:50:00"")}
vqlkdk9b

vqlkdk9b6#

你可以使用npm中的npm i moment包,并使用diff函数,如下所示:moment.duration(nowMoment.diff(updateMoment)).as("hours")
差异可以按天、小时或分钟计算。

s4n0splo

s4n0splo7#

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)将是星期日。

与时刻#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
yqlxgs2m

yqlxgs2m8#

这是我在应用程序中使用的函数。不需要任何库

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;

}

g6baxovj

g6baxovj9#

React时间前

https://www.npmjs.com/package/react-time-ago
react-time-ago完全符合您的要求,而且更直接
<ReactTimeAgo date={createdAt} />
让我开心的主要特点:

  • 将自动转换未来的日期为“在5分钟内”
  • 提供包含完整日期字符串的工具提示
  • 工作与最小的设置(有它的工作在2分钟)

相关问题