Search code examples
javascriptdatetimemomentjsmoment-timezone

How to sort moment-timezone list?


I want to show the moment-timezone list in ascending order in a drop-down menu. By default, those are sorted in alphabetical order. But, my requirement is to sort them by GMT in ascending order.

before soring:

[
  '(GMT+00:00) Africa/Abidjan',
  '(GMT+00:00) Africa/Accra',
  '(GMT+03:00) Africa/Addis_Ababa',
  '(GMT+01:00) Africa/Algiers',
  '(GMT+03:00) Africa/Asmara',
  '(GMT+03:00) Africa/Asmera',
  '(GMT+00:00) Africa/Bamako',
  '(GMT+01:00) Africa/Bangui',
]

after sorting:

[
  '(GMT+00:00) Africa/Abidjan',
  '(GMT+00:00) Africa/Accra',
  '(GMT+00:00) Africa/Bamako',
  '(GMT+01:00) Africa/Algiers',
  '(GMT+01:00) Africa/Bangui',
  '(GMT+03:00) Africa/Addis_Ababa',
  '(GMT+03:00) Africa/Asmera',
  '(GMT+03:00) Africa/Asmara',
]


Solution

  • Shorter than yours, Ashik. No need to access the timezone from the array twice

    const getTimeZoneList = moment.tz.names()
      .map(t => `(GMT${moment.tz(t).format("Z")}) ${t}`);
    const sortByZone = (a,b) => { 
      let [ahh,amm] = a.split("GMT")[1].split(")")[0].split(":"); 
      let [bhh,bmm] = b.split("GMT")[1].split(")")[0].split(":");
      return (+ahh*60+amm) - (+bhh*60+bmm)
    };
    console.log(getTimeZoneList.sort(sortByZone))
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.27/moment-timezone-with-data-2012-2022.min.js"></script>