【问题标题】:Sort String Json Date排序字符串 Json 日期
【发布时间】:2019-11-07 11:18:51
【问题描述】:

我从对象数组中获取如下日期值:"/Date(1560458281000)/"。我只想按降序和升序排列这些日期。我对纯 JavaScript 和/或 moment.js 的任何示例持开放态度。顺便说一下,小时和分钟很重要。我会显示为2014/10/29 4:50

let dateSorted = this.props.myObj.sort(function(a,b) {
  sorted= new Date(Number(a.Date.replace(/\D/g, ''))) - new 
  Date(Number(b.Date.replace(/\D/g, '')))
  return sorted;
})

此代码不起作用。

【问题讨论】:

  • 一些真实的样本数据在这里会有所帮助:)

标签: javascript json date momentjs


【解决方案1】:

此代码应将代码从高到低排序,日期格式为:

data = [{Date:"/Date(1560457284000)/"},{Date: "/Date(1560458274000)/"},{Date:"/Date(1560458192000)/"}]

sorted = data.sort(({Date:a}, {Date:b}) => +b.replace(/\D/g, '') - +a.replace(/\D/g, ''))

sorted = sorted.map(({Date}) => ({Date: moment(+Date.replace(/\D/g, '')).format('YYYY/MM/DD H:mm')}))
console.log(sorted)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

【讨论】:

    【解决方案2】:

    使用Array#map 将您的字符串数组转换为momentjs 实例数组,然后使用Array#sorta - b 作为返回值(或b - a 以降序排列)对其进行排序。

    dates.map(d => moment(+d.replace(/\D/g, ''))).sort((a, b) => a - b);
    

    例子:

    let dates = [
      '/Date(1560458281000)/',
      '/Date(1560454528989)/',
      '/Date(1560450204150)/',
      '/Date(1560458450489)/'
    ];
    
    // Replaces.
    dates = dates.map(d => moment(+d.replace(/\D/g, '')));
    
    // Sorts in ascending order (return b - a for desc).
    dates.sort((a, b) => a - b);
    
    // "dates" is containing your sorted date in momentjs instances now.
    console.log(dates);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

    【讨论】:

    • 问题在于你只是对日期进行排序,也许他想对包含日期的对象进行排序,所以不能使用地图。这是我的理解。
    【解决方案3】:

    你应该小心你的 sorted 变量,它缺少 const / let 初始化器,我会写:

    let dateSorted = this.props.differences.sort(function(a,b) {
      const timeA = Number(a.Date.replace(/\D/g, ''))
      const timeB = Number(b.Date.replace(/\D/g, ''))
    
      return timeA - timeB;
    })
    

    而且由于您的日期是时间戳格式,您甚至不需要将它们转换为日期来比较它们,您可以直接减去数字。

    更简单的方法是使用localeCompare:

    let dateSorted = this.props.differences.sort(function (a, b) {
      return a.Date.localeCompare(b.Date)
    })
    

    因为您的日期将按字母顺序正确排序。

    【讨论】:

    • @reeeact 你能显示myObj 的实际值吗?另外,你能扩展一下究竟是什么不起作用吗?
    • 您可以在此处添加一元运算符 (+) 而不是使用 Number()
    • @Kobe 我不喜欢使用运算符类型强制,我发现明确的Number 更加明确和不那么骇人听闻。他的原始代码也使用Number
    猜你喜欢
    • 2020-12-14
    • 1970-01-01
    • 2012-11-09
    • 2014-02-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    相关资源
    最近更新 更多