【问题标题】:How to sort/order a list according to time in 00:00 format?如何根据 00:00 格式的时间对列表进行排序/排序?
【发布时间】:2021-04-21 15:23:56
【问题描述】:

我有这个列表,我想根据时间 ["timein"] 在我的屏幕上对其进行排序。有谁知道我该怎么做?

[{weekday: segunda, description: Química, nametag: Estudos, numbercolortags: [33, 150, 243], timein: 18:30, timeout: 20:00}, {weekday: segunda, description: Física, nametag: Estudos, numbercolortags: [33, 150, 243], timein: 11:00, timeout: 12:00}, {weekday: segunda, description: Biologia, nametag: Estudos, numbercolortags: [33, 150, 243], timein: 22:00, timeout: 23:00}]

【问题讨论】:

标签: flutter dart


【解决方案1】:

可能的解决方案:

void main() {
  json.sort((x, y) => '${x['time']}'.seconds.compareTo('${y['time']}'.seconds));
  for (final element in json) {
    print(element);
  }
}

final json = [
  {'id': 1, 'time': '10:00:01'},
  {'id': 3, 'time': '30:00'},
  {'id': 2, 'time': '20:00'},
  {'id': 4, 'time': '40:00'},
  {'id': 0, 'time': '10:00'},
];

extension _Time on String {
  int get seconds {
    var hours = 0;
    var minutes = 0;
    var seconds = 0;
    final parts = split(':');
    switch (parts.length) {
      case 2:
        minutes = _toInt(parts[0], 59);
        seconds = _toInt(parts[1], 59);
        break;
      case 3:
        hours = _toInt(parts[0], 23);
        minutes = _toInt(parts[1], 59);
        seconds = _toInt(parts[2], 59);
        break;
      default:
        _error();
    }

    return hours * 3600 + minutes * 60 + seconds;
  }

  void _error() {
    throw FormatException('Invalid time format: $this');
  }

  int _toInt(String part, int max) {
    final result = int.tryParse(part, radix: 10);
    if (result == null) {
      _error();
    }

    if (result < 0 || result > max) {
      _error();
    }

    return result;
  }
}

结果:

{id: 0, time: 10:00}
{id: 1, time: 10:00:01}
{id: 2, time: 20:00}
{id: 3, time: 30:00}
{id: 4, time: 40:00}

【讨论】:

  • 最好的感谢是接受的答案(接受并赞成)。
  • 谢谢。你问,别人回答。那你给分。这些是良好形式的规则。我还评价了你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
  • 1970-01-01
  • 2021-08-24
  • 2015-01-08
  • 2019-03-14
  • 2019-12-08
  • 1970-01-01
相关资源
最近更新 更多