首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >2次显示差异

2次显示差异
EN

Stack Overflow用户
提问于 2018-06-29 16:00:44
回答 1查看 95关注 0票数 0

它给我这样,而不是显示多少小时它显示“小时”,但真正的问题是,即使日期是今天和时间应该显示分钟它给我的小时。我必须显示基于条件的时间,如果订单已经被提前几分钟,它应该显示"1 min",如果几个小时前,然后"18 hr",如果它不是目前的日期,它应该显示在"29/06/18"格式的日期。感谢使用moment.js提供的任何帮助。

这是我的代码:

导出类通知扩展了PureComponent {

代码语言:javascript
复制
  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数据格式如下

代码语言:javascript
复制
{
    id: "1",
    icon: "water",
    location:
        "Your booking water",
    dateTime: "2018-06-12T20:20:52.123Z"
}

提前感谢

EN

回答 1

Stack Overflow用户

发布于 2018-06-29 19:17:06

您首先需要测试日期是否为“今天”,如果不是,则返回所需格式的日期字符串。否则,以所需格式返回前一时间。

既然您想要与moment.js返回的默认"from now“不同的东西,并且编写自己的代码并不困难,那么您也可以这样做。见下文。

编辑

上面的函数期望获得一个Date对象,所以如果你的源JSON是:

代码语言:javascript
复制
'{"id":"1","icon":"water","location":"Your booking water","dateTime":"2018-06-12T20:20:52.123Z"}'

然后,您需要获取dateTime属性并将其转换为日期。请注意,所提供的字符串将被解析为UTC (给定Z时区标识符),但函数的结果将基于主机时区偏移。

代码语言:javascript
复制
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))}`);
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"></script>

注意:通常的警告适用于使用内置解析器:如果您可以保证字符串将严格遵守ECMA-262中的时区格式(例如"Z“或±HH:mm),那么使用它是相当安全的。否则,使用moment解析器。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51097017

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档