skip to Main Content

I’ve got a list of data which also contains ISO8601 DateTime format. How can I sort it by time not date?

[2022-12-06T22:37:49.292343,
 2022-12-06T18:37:49.300045,
 2022-12-06T15:37:49.307976]

2

Answers


  1. To sort the list of dates by their hour, you can use:

    void main() {
      final dates = [
        '2022-12-06T22:39:50.292343',
        '2022-12-06T18:37:49.300045',
        '2022-12-06T15:37:49.307976'
      ];
      
      dates
          .sort((a, b) => DateTime.parse(a).hour.compareTo(DateTime.parse(b).hour));
      print(dates);
    }
    

    Output:

    [2022-12-06T15:37:49.307976, 2022-12-06T18:37:49.300045, 2022-12-06T22:39:50.292343]
    
    Login or Signup to reply.
    1. Parse the strings to DateTime objects.
    2. If you want to ignore the date and sort only by time, create new DateTime objects that copy the times and that all use the same date.
    3. Sort by those new DateTime objects.
    void main() {
      var dateTimeStrings = [
        '2022-12-01T22:37:49.292343',
        '2022-12-02T18:37:49.300045',
        '2022-12-03T15:37:49.307976',
      ];
    
      /// Replaces the date portion of a [DateTime] with a fixed date,
      /// retaining the time portion.
      ///
      /// The returned [DateTime] object will be in UTC.
      ///
      /// In Dart 2.19, this implementation can be simplified with the
      /// [DateTime.copyWith] extension.
      DateTime clobberDate(DateTime dateTime) => DateTime.utc(
        2022,
        1,
        1,
        dateTime.hour,
        dateTime.minute,
        dateTime.second,
        dateTime.millisecond,
        dateTime.microsecond,
      );
      
      dateTimeStrings.sort((a, b) {
        var dt1 = clobberDate(DateTime.parse(a));
        var dt2 = clobberDate(DateTime.parse(b));
        return dt1.compareTo(dt2);
      });
      
      dateTimeStrings.forEach(print);
    }
    

    which prints:

    2022-12-03T15:37:49.307976
    2022-12-02T18:37:49.300045
    2022-12-01T22:37:49.292343
    

    Note that the above sort callback could be unnecessarily expensive for long lists since it could call DateTime.parse multiple times on the same Strings. It’d be better to convert your List<String> to a List<DateTime> first and then sort that. Or, if you must start and end with Strings, you could use a Schwartzian transform.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search