【问题标题】:show difference in 2 times显示2次差异
【发布时间】:2018-12-08 08:53:15
【问题描述】:

它给了我这样的信息,而不是显示它“以小时为单位”显示了多少小时,但真正的问题是,即使日期是今天,时间应该以分钟为单位显示,它以小时为单位给我.. 我必须根据以下条件显示时间@。使用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"
}

提前致谢

【问题讨论】:

    标签: javascript date react-native format momentjs


    【解决方案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));
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"&gt;&lt;/script&gt;

    【讨论】:

    • 感谢您的帮助.....但我不想显示几小时前或几天前。
    • 非常感谢如果我得到这种格式的日期 "2018-06-12T20:20:52.123Z"
    • 如何将“2018-06-12T20:20:52.123Z”转换为“DD/MM/YYYY HH:mm”格式。
    • @abhijith 你可以在传递它之前将它包裹在new Date(data.dateTime)中,看看我的sn-p中的例子。
    • @abhijith 我编辑了解决方案,因此它从输入中正确构造了日期。
    【解决方案2】:

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

    由于您想要与 moment.js 返回的默认“从现在开始”不同的内容,并且编写自己的内容并不难,您不妨这样做。见下文。

    编辑

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

    '{"id":"1","icon":"water","location":"Your booking water","dateTime":"2018-06-12T20:20:52.123Z"}'
    

    那么您需要获取 dateTime 属性并将其转换为日期。请注意,提供的字符串将被解析为 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))}`);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"&gt;&lt;/script&gt;

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

    【讨论】:

    • 感谢您的努力,但如果我使用 date.getDate() 它会给我一个错误,说 undefined 不是函数。这正是我需要的..请帮助
    • 您需要将日期传递给函数,例如:formatDate(new Date(obj.dateTime)),相当于formatDate(new Date("2018-06-12T20:20:52.123Z"))。但请确保格式正确,任何与 ECMA-262 中 ISO 8601 版本的偏差都可能在不同的浏览器中产生不同的结果。
    • 我已经编辑了上面的代码我在哪里添加这个功能请帮助我..我是新手。
    • @abhijith — 将 this.getDateFormatted 更改为 this.formatDate,因为这是您的函数名称(或将函数名称更改为 getDateFormatted)。
    • 仍然出现同样的错误...顺便问一下这个有什么用- (diff/6e4 | 0)
    【解决方案3】:

    使用 momentjsfromNow()。它会给你想要的输出。

    var duration = moment("29/06/18", "DD/MM/YYYY").fromNow(); // in moment("pass your timestamp/valid date")
    
    console.log(duration);
    &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.js"&gt;&lt;/script&gt;

    【讨论】:

    • 是的,这就是实现它的功能。只是给@abhijith 的一个小提示,您需要将“29/06/18”转换为应该做的日期var d = new Date("29/06/18");。然后var duration = moment(d).fromNow();
    • @AdrianGrzywaczewski 。不起作用。检查我的答案,了解如何在 moment() 中传递日期。
    • 感谢您的帮助...但我不想硬编码今天的日期是否有任何解决方法
    • @abhijith 问题是您没有在问题中提供足够的信息。添加一些输入日期的示例,以便我可以为您提供相应的解决方案
    • @VicJordan 我已经编辑了问题,请参考。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多