它给了我这种方式,而不是显示“小时”显示了多少小时,但真正的问题是,即使日期是今天,时间应该以分钟为单位显示。
我必须根据以下条件显示时间:如果订单已提前几分钟下达,则应显示"1 min"
,如果几小时前则应显示"18 hr"
,如果不是当前日期,则应显示日期格式"29/06/18"
。使用moment.js
可以帮助您。
这是我的代码:
导出类通知扩展了PureComponent {
constructor(props) {
super(props);
this.state = {
notificationsData: null,
isLoading: true
};
}
componentDidMount() {
if (notifications) {
this.setState({
notificationsData: notifications.data,
isLoading: false
});
} else {
this.setState({ isLoading: false });
}
}
renderIconBadge(icon) {
return (
<View style={styles.iconBagdeContainer}>
<Icon name={icon} size={scale(16)} />
</View>
);
}
getDateFormatted(dateTime) {
var date = moment(dateTime, "DD/MM/YYYY HH:mm").isValid() ?
moment(dateTime, "DD/MM/YYYY HH:mm")
: moment(new Date(dateTime), "DD/MM/YYYY HH:mm");
var diff = date.fromNow();
if (diff.indexOf("minute") > -1) {
return diff.substring(0, 2).trim() + " mins";
} else if (diff.indexOf("hour") > -1) {
//If it's yesterday
if(date.day() != moment().day()){
return date.format("DD/MM/YYYY");
}
return diff.substring(0, 2).trim() + " hrs";
} else {
return date.format("DD/MM/YYYY");
}
}
renderNotificationCard = ({ item }) => {
return (
<Card style={styles.notificationCardContainer}>
<View
style={{
flexDirection: "row"
}}
>
{/* <View style={{ flexDirection: "row" }}> */}
{this.renderIconBadge(item.icon)}
<View
style={{
marginLeft: scale(12)
}}
>
<Text
style={styles.location}
numberOfLines={3}
ellipsizeMode="tail"
>
{item.location}
</Text>
<View style={{ flexDirection: "row" }}>
<ClickView onPress={() => {}}>
<Text style={styles.viewBooking}>
View Booking
</Text>
</ClickView>
<Text style={styles.dateFormat}>
{this.getDateFormatted(item.dateTime)}
</Text>
</View>
</View>
{/* </View> */}
</View>
</Card>
);
};
renderNotificationList() {
const { notificationsData } = this.state;
return (
<View style={{ marginTop: scale(10), marginBottom: scale(100) }}>
{notificationsData.notification.length !== 0 ? (
<FlatList
data={this.state.notificationsData.notification}
renderItem={this.renderNotificationCard}
/>
) : (
<View
style={{
marginTop: scale(100),
alignItems: "center"
}}
>
<Image source={Images.noTaskImg} />
<Text
style={{
marginTop: scale(20),
fontSize: scale(18),
fontWeight: "600",
color: Colors.body
}}
>
No Notifications found.
</Text>
</View>
)}
</View>
);
}
render() {
const { isLoading } = this.state;
return (
<ThemeView
theme="dark"
style={styles.mainContainer}
rightButton="close"
onRightButtonPress={() => {
this.props.navigation.goBack();
}}
>
{isLoading ? (
<ProgressBar />
) : (
<View>
<View
style={{ marginTop: scale(Metrics.headerHeight) }}
>
<Text style={styles.newTasks}>New Tasks</Text>
{this.renderNotificationList()}
</View>
</View>
)}
</ThemeView>
);
}
}
JSON数据格式如下
{
id: "1",
icon: "water",
location:
"Your booking water",
dateTime: "2018-06-12T20:20:52.123Z"
}
预先感谢
答案 0 :(得分:1)
实际上,您可以使用fromNow()来检查差异,并根据结果返回您的自定义字符串。
这应该是您的功能:
var getDateFormatted = function(dateTime) {
var date = moment(dateTime, "DD/MM/YYYY HH:mm").isValid() ?
moment(dateTime, "DD/MM/YYYY HH:mm")
: moment(new Date(dateTime), "DD/MM/YYYY HH:mm");
var diff = date.fromNow();
if (diff.indexOf("minute") > -1) {
return diff.substring(0, 2).trim() + " mins";
} else if (diff.indexOf("hour") > -1) {
//If it's yesterday
if(date.day() != moment().day()){
return date.format("DD/MM/YYYY");
}
return diff.substring(0, 2).trim() + " hrs";
} else {
return date.format("DD/MM/YYYY");
}
}
var getDateFormatted = function(dateTime) {
var date = moment(dateTime, "DD/MM/YYYY HH:mm").isValid() ?
moment(dateTime, "DD/MM/YYYY HH:mm") :
moment(new Date(dateTime), "DD/MM/YYYY HH:mm");
var diff = date.fromNow();
if (diff.indexOf("minutes") > -1) {
return diff.substring(0, 2).trim() + " mins";
} else if (diff.indexOf("hour") > -1) {
if (date.day() != moment().day()) {
return date.format("DD/MM/YYYY");
}
return diff.substring(0, 2).trim() + " hrs";
} else {
return date.format("DD/MM/YYYY");
}
}
var data = {
id: "1",
icon: "water",
location: "Your booking water",
dateTime: "2018-06-12T20:20:52.123Z"
};
console.log(getDateFormatted("28/06/2018 23:00"));
console.log(getDateFormatted("29/06/2018 11:50"));
console.log(getDateFormatted("28/06/2018 01:00"));
console.log(getDateFormatted(data.dateTime));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
答案 1 :(得分:1)
您首先需要测试日期是否为“今天”,否则,请以所需格式返回日期字符串。否则,以所需的格式返回时间。
由于您想要的是不同于moment.js返回的默认“从现在开始”的东西,并且编写自己的东西并不困难,因此您最好这样做。见下文。
上面的函数希望获得一个Date对象,因此,如果您的源JSON是:
'{"id":"1","icon":"water","location":"Your booking water","dateTime":"2018-06-12T20:20:52.123Z"}'
然后您需要获取 dateTime 属性并将其转换为Date。请注意,提供的字符串将被解析为UTC(给定Z时区标识符),但函数的结果将基于主机时区偏移量。
function formatDate(date) {
var d = new Date();
var diff = d - date;
// If yesterday, return a formatted date
if (d.getDate() != date.getDate()) {
return moment(date).format('DD/MM/YYYY');
}
// If diff less than an hour ago, return minutes
if (diff < 3.6e6) {
return (diff/6e4 | 0) + ' min';
}
// Otherwise, return hours
return (diff/3.6e6 | 0) + ' hr';
}
// Some test dates
var a = new Date();
// 3 minutes ago
var b = new Date(a.setMinutes(a.getMinutes() - 3));
// 1 hour and 3 minutes ago
var c = new Date(a.setHours(a.getHours() - 1));
// 2 hour and 3 minutes ago
var d = new Date(a.setHours(a.getHours() - 1));
// 1 day, 2 hour and 3 minutes ago
a.setDate(a.getDate() - 1);
[b,c,d,a].forEach(function(d) {
console.log(`${moment(d).format('DD/MM/YY HH:mm')} => ${formatDate(d)}`);
});
// Using sample JSON:
var jsonTxt = '{"id":"1", "icon":"water", "location":"Your booking water", "dateTime":"2018-06-12T20:20:52.123Z"}';
var obj = JSON.parse(jsonTxt);
// Without moment.js
console.log(formatDate(new Date(obj.dateTime)));
// With moment.js
console.log(formatDate(moment(obj.dateTime).toDate()));
// Make dateTime 3 minutes ago
var s = b.toISOString(); // UTC 3 mins ago
obj.dateTime = s;
console.log(`${s} => ${formatDate(new Date(obj.dateTime))}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>
NB。通常的警告适用于使用内置解析器:如果您可以保证字符串严格遵守ECMA-262中带有时区的格式(例如“ Z”或±HH:mm),则使用起来相当安全。否则,请使用矩分析器。
答案 2 :(得分:0)
使用 momentjs 中的fromNow()。它将为您提供所需的输出。
var duration = moment("29/06/18", "DD/MM/YYYY").fromNow(); // in moment("pass your timestamp/valid date")
console.log(duration);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>