javascript - 用javascript反应显示相对时间
问题描述
我正在创建一个反应应用程序,我正在尝试使用 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 />
);
}
在我的数据库中,我的日期以这种格式保存“Sun Nov 10 2019 03:58:48 GMT-0500 (Colombia Standard Time)”
解决方案
这并不能直接回答您的问题,但您可能确实需要考虑处理日期和时间的时刻。使用 moment 或类似的库,您可以将函数替换为:
moment(previousDate).fromNow();
编辑:如果您不能使用库,我建议您在我的评论中将所有内容转换为数字 Unix 时间戳,以使数学更简单。这是一个假设传入日期已经用getTime()
or转换的版本valueOf()
:
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()));
我没有对所有单位进行单数/复数处理,但你明白了。如果您在将日期带入函数之前转换日期,这只是纯粹的算术,这可以通过内置的 JS 功能轻松完成。如果您知道它们的格式,您甚至可以在函数内部转换它们。
推荐阅读
- javascript - React Hooks 带有单独倒计时的多个警报
- python - 需要验证表格内的文本(Python、Selenium)
- amazon-web-services - 是否可以使用 AWS Glue 连接来创建数据源?
- postgresql - 需要修复我的 TimescaleDB 数据库中的时间戳(提供给 TO_TIMESTAMP 的秒数不正确,正好是 1000 倍)
- python - 如何有条件地设置列值
- vue.js - 我需要新鲜的眼光来修复 VUE 道具不起作用
- javascript - 使用 javascript 创建 blob url
- javascript - 数组赋值后为空
- swift - 如何在动画后强制重置 tableview 中的可访问性标识符?
- python - 在 python 中对 API 的请求。并在 tkinter 窗口中显示