Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用javascript显示相对时间_Javascript_Reactjs - Fatal编程技术网

使用javascript显示相对时间

使用javascript显示相对时间,javascript,reactjs,Javascript,Reactjs,我正在创建一个react应用程序,我正在尝试用javascript显示相对时间的日期,例如“2年前”,我创建了一个函数,将字符串转换为日期,并计算出日期之间的差异,以显示时间差,但我正在显示NaN 这是我的函数和我的组件的渲染 timeDifference = () => { const { products } = this.state; var previousdate = new Date(products.date); var previousmnth =

我正在创建一个react应用程序,我正在尝试用javascript显示相对时间的日期,例如“2年前”,我创建了一个函数,将字符串转换为日期,并计算出日期之间的差异,以显示时间差,但我正在显示NaN

这是我的函数和我的组件的渲染

timeDifference = () => {
    const { products } = this.state;
    var previousdate = new Date(products.date);
    var previousmnth = ("0" + (previousdate.getMonth()+1)).slice(-2);
    var previousday  = ("0" + previousdate.getDate()).slice(-2);
    var previoushours  = ("0" + previousdate.getHours()).slice(-2);
    var previousminutes = ("0" + previousdate.getMinutes()).slice(-2);
    var previous = [ previousdate.getFullYear(), previousmnth, previousday, previoushours, previousminutes ].join("-");

    var current = new Date();

    var minutes = 60 * 1000;
    var hours = minutes * 60;
    var days = hours * 24;
    var months = days * 30;
    var years = days * 365;

    var elapsed = current - previous;

    if (elapsed < minutes) {
         return Math.round(elapsed/1000) + ' seconds ago';   
    }

    else if (elapsed < hours) {
         return Math.round(elapsed/minutes) + ' minutes ago';   
    }

    else if (elapsed < days ) {
         return Math.round(elapsed/hours ) + ' hours ago';   
    }

    else if (elapsed < months) {
         return 'approximately ' + Math.round(elapsed/days) + ' days ago';   
    }

    else if (elapsed < years) {
         return 'approximately ' + Math.round(elapsed/months) + ' months ago';   
    }

    else {
         return 'approximately ' + Math.round(elapsed/years ) + ' years ago';   
    }
}



  render() {

  const Prods = () => {
    return (
    <div>
       <div className="row">
           <button onClick={this.sortPrice}>sort by price lower to higher</button>
           <button onClick={this.sortSize}>sort by size small to big</button>
           <button onClick={this.sortId}>sort by Id</button>  
        </div>
            {products.map(product =>
            <div className="row">
                <div className="col-3">
                  <p> Price: ${(product.price/100).toFixed(2)}</p>
                </div>

                <div className="col-3">
                  <p style={{fontSize: `${product.size}px`}} > {product.face}</p>
                </div>

                <div className="col-3">
                  <p>Published: {this.timeDifference()}</p>
                </div>
            </div> 
            )}
            <p>"~END OF CATALOG~"</p>
      </div>
    );
};

    const { products, isLoading, error } = this.state;
    if (error) {
      return <p>{error.message}</p>;
    }
    if (isLoading) {
      return  <Loading />;
    }
    return (
      <Prods />

    );
  }
时差=()=>{
const{products}=this.state;
var previousdate=新日期(products.Date);
var previousmnth=(“0”+(previousdate.getMonth()+1)).slice(-2);
var previousday=(“0”+previousdate.getDate()).slice(-2);
var previoushours=(“0”+previousdate.getHours()).slice(-2);
var previousminutes=(“0”+previousdate.getMinutes()).slice(-2);
var previousdate=[previousdate.getFullYear(),previousmnth,previousday,previoushours,previousminutes]。加入(“-”;
var current=新日期();
var分钟=60*1000;
var小时=分钟*60;
var天数=小时*24;
var月数=天*30;
var年=天*365;
var经过=当前-上一个;
如果(已用时间<分钟){
返回Math.round(经过/1000)+“秒前”;
}
否则如果(已用时间<小时){
返回Math.round(已用/分钟)+“分钟前”;
}
否则如果(已用天数<天){
返回Math.round(已用/小时)+“小时前”;
}
否则,如果(已过去<个月){
返回“大约”+数学圆(已用/天)+“几天前”;
}
否则,如果(经过<年){
返回“大约”+数学舍入(已过/个月)+“个月前”;
}
否则{
返回“大约”+数学圆(已用/年)+“年前”;
}
}
render(){
const Prods=()=>{
返回(
按价格从低到高排序
按大小从小到大排序
按Id排序
{products.map(product=>
价格:${(产品价格/100).toFixed(2)}

{product.face}

已发布:{this.timeDifference()}

)} “~目录末尾~”

); }; const{products,isLoading,error}=this.state; 如果(错误){ 返回{error.message}

; } 如果(孤岛加载){ 返回; } 返回( ); }

在我的数据库中,我的日期以以下格式保存:“Sun Nov 10 2019 03:58:48 GMT-0500(哥伦比亚标准时间)”

您拥有
日期类型的
当前
,以及
字符串的
以前的
<代码>日期-字符串=NaN
。您只需执行以下操作:

var-appead=current-productsdate;

这不直接回答你的问题,但你可能真的想考虑处理日期和时间。使用矩或类似的库,您可以将函数替换为:

moment(previousDate).fromNow();
编辑:如果您不能使用库,我建议将所有内容都转换为数字Unix时间戳,以简化计算。这里有一个版本,假设传入日期已经用
getTime()
valueOf()转换过:

const timeAgo=(prevDate)=>{
const diff=编号(新日期())-prevDate;
常数分钟=60*1000;
常数小时=分钟*60;
常数天=小时*24;
施工月=天*30;
施工年份=天*365;
开关(真){
案例差异<分钟:
常数秒=数学圆(差值/1000);
返回`${seconds}${seconds>1?'seconds':'second'}前`
案例差异<小时:
返回数学圆(差异/分钟)+“分钟前”;
病例差异<天:
返回数学圆(差异/小时)+“小时前”;
病例差异<月份:
返回Math.round(diff/天)+“几天前”;
病例差异<年份:
返回Math.round(差异/月)+“月前”;
病例差异>年份:
返回数学。四舍五入(差异/年)+“年前”;
违约:
返回“”;
}
};
...
log(timeAgo(新日期(“2018年10月25日星期四”).getTime());

我没有对所有单元进行单数/复数处理,但你明白了。如果在将日期引入函数之前转换日期,这只是一个纯粹的算术运算,使用内置的JS功能可以轻松完成。如果您知道它们的格式,您甚至可以在函数中转换它们。

我创建了一个简单的React组件,使用moment.js在我的项目中实现这一点-在这里共享,以防其他人遇到此问题。

执行此操作时,我会出现下一个错误:“productsdate”未定义无未定义,如果执行var-appeased=current-products.date;我明白了,你确定你没有删除
productsdate
?您的函数应该这样启动:
imeDifference=()=>{const{products}=this.state;var-previousdate=new-Date(products.Date);var-current=new-Date();var appeased=current-previousdate;..
谢谢Andres,我用上述答案解决了我的问题是的,我想用moment,但我被要求不要使用库或插件来做这件事。你的日期是什么格式的?如果你将上一个日期转换为时间戳,那么你就可以直接做数学了。我的日期以这种格式保存“Sun Nov 10 2019 03:58:48 GMT-0500(哥伦比亚标准时间)”Momentjs使用Nextjs为第一页加载增加了约70KB,这要轻得多:)
const timeAgo = (prevDate) => {
        const diff = Number(new Date()) - prevDate;
        const minute = 60 * 1000;
        const hour = minute * 60;
        const day = hour * 24;
        const month = day * 30;
        const year = day * 365;
        switch (true) {
            case diff < minute:
                const seconds = Math.round(diff / 1000);
                 return `${seconds} ${seconds > 1 ? 'seconds' : 'second'} ago`
            case diff < hour:
                return Math.round(diff / minute) + ' minutes ago';
            case diff < day:
                return Math.round(diff / hour) + ' hours ago';
            case diff < month:
                return Math.round(diff / day) + ' days ago';
            case diff < year:
                return Math.round(diff / month) + ' months ago';
            case diff > year:
                return Math.round(diff / year) + ' years ago';
            default:
                return "";
        }
    };

...

    console.log(timeAgo(new Date("Thu Oct 25 2018").getTime()));