Ahmed AL-Dilli
Ahmed AL-Dilli

Reputation: 15

How can I organise my list of months using Dart/Flutter?

I have a list as follows:

myList = ['October 2022', 'January 2023', 'December 2022', 'February 2023', 'November 2022']

is there a function that can take this list and return the list in order of month like this:

newList = ['October 2022', 'November 2022', 'December 2022', 'January 2023', 'February 2023']

Thank you guys very much would greatly appreciate help 🙏

Upvotes: 0

Views: 55

Answers (1)

Peter Koltai
Peter Koltai

Reputation: 9754

You can do it using intl package. It is important to have a locale set that has these month names, for example en-EN.

So first you have to create dates from the original text values, then sort these and convert it back.

Check tis code (after adding the package):

import 'package:intl/intl.dart';

Intl.defaultLocale = 'en-EN';

final myList = [
  'October 2022',
  'January 2023',
  'December 2022',
  'February 2023',
  'November 2022'
];

// date format used to parse and format
final DateFormat myDateFormat = DateFormat("MMMM yyyy");

// create a list of DateTime objects from the list of strings
final myDates = myList.map((e) => myDateFormat.parse(e)).toList();

// sort the DateTime objects using milliseconds passed since UNIX epoch
myDates.sort(
    (a, b) => a.millisecondsSinceEpoch.compareTo(b.millisecondsSinceEpoch));

// convert back to list of strings
final myDatesAsText = myDates.map((e) => myDateFormat.format(e)).toList();

(Since there is no day in your list of strings, every DateTime will be the first day in the month, and the time 00:00:00, but is won't affect order.)

Upvotes: 1

Related Questions