1.传入的值是一个秒的时间戳,要求当返回时间距离现在在24个小时之内,显示为多少小时或多少分钟之前,大于24个小时后直接显示年月日时分秒。
//timestamp.js
function timestamp(createdAt) {
const date = new Date();
const currentTimestamp = date.getTime(); //获取当前时间的时间戳
const result = (currentTimestamp - createdAt * 1000) / (1000 * 60);//两个时间戳之间相隔的分钟数
if (result > 24 * 60) {
this.createTime = this.timestampChangeData(createdAt);
} else if (result > 60 && result < 24 * 60) {
this.createTime = Math.floor(result / 60) + '小时前';
} else {
this.createTime = Math.floor(result) + '分钟前';
}
return this.createTime;
}
// 时间戳转日期
timestampChangeData = (da) => {
const times = new Date(da * 1000);
const year = times.getFullYear();
const month = times.getMonth() + 1;
const day = times.getDate();
const hour = times.getHours();
const minutes = times.getMinutes();
const seconds = times.getSeconds();
return `${year}-${this.add0(month)}-${this.add0(day)} ${this.add0(hour)
}:${this.add0(minutes)}:${this.add0(seconds)}`;
};
// 补0
add0 = number => number < 10 ? `0${number}` : number;
消息列表:
//messageItem.js
render() {
const {data} = this.props;
const createdAt = get(data, 'item.created_at');
return (
<Text>{timestamp(createdAt)}</Text>
);
}
}
2.传入的两个值分别是开始和结束的时间戳,要求实现
XXXX年XX月XX日 周X XX:XX:XX - XX:XX:XX (X小时)效果
import moment from 'moment';
render() {
const time = this.timestampStringData(begin, end);
return(
<Text>{time}</Text>
)
}
// 时间戳转日期
timestampStringData = (begin, end) => {
const timesBegin = moment.unix(begin);
const timesEnd = moment.unix(end);
const week = timesBegin.day();
const data = `${timesBegin.format(ext('orderDateFormat'))} ${this.changeWeek(week)}`;
const time = `${timesBegin.format(ext('orderMinuteFormat'))} - ${timesEnd.format(ext('orderMinuteFormat'))}`;
const hours = stringFormat(ext('resultHour'), (timesEnd.diff(timesBegin, 'minutes') * 1.0 / 60));
return `${data} ${time} (${hours})`;
};
changeWeek = (week) => {
let weekDay = '';
const weekDayArray = [ext('sunday'), ext('monday'), ext('tuesday'), ext('wednesday'),
ext('thursday'), ext('friday'), ext('saturday')];
weekDay = weekDayArray[week];
return weekDay;
}
// 时间戳计算相隔小时数
getHours = (begin, end) => {
const dateTime = (end - begin) * 1000;
const leave = dateTime % (24 * 3600 * 1000);
const hours = leave / (3600 * 1000);
return hours;
}
网友评论