Home > Net >  using moment js utc offset to filter an array of objects
using moment js utc offset to filter an array of objects

Time:01-24

i have an array of timezones that looks as follows

{name: '(UTC) Coordinated Universal Time', offset: '00:00:00', id: 'UTC'}
{name: '(UTC 00:00) Dublin, Edinburgh, Lisbon, London', offset: '00:00:00', id: 'GMT Standard Time'}
{name: '(UTC 03:00) Istanbul', offset: '03:00:00', id: 'Turkey Standard Time'}
{name: '(UTC 04:00) Astrakhan, Ulyanovsk', offset: '04:00:00', id: 'Astrakhan Standard Time'}

so i am trying to filter the above list to find the matching utc offset that i give it as follows

this.timezones.filter(x=> moment().utcOffset(x.offset).utcOffset() == '240')

so 240 minutes is "04:00:00" offset from the timezone array so my expected output should be

{name: '(UTC 04:00) Astrakhan, Ulyanovsk', offset: '04:00:00', id: 'Astrakhan Standard Time'}

But it just returns an empty array cause it cant find it. What am i doing wrong?

CodePudding user response:

You can do it like this:

let objects = [
  { name: "(UTC) Coordinated Universal Time", offset: "00:00:00", id: "UTC" },
  {
    name: "(UTC 00:00) Dublin, Edinburgh, Lisbon, London",
    offset: "00:00:00",
    id: "GMT Standard Time",
  },
  {
    name: "(UTC 03:00) Istanbul",
    offset: "03:00:00",
    id: "Turkey Standard Time",
  },
  {
    name: "(UTC 04:00) Astrakhan, Ulyanovsk",
    offset: "04:00:00",
    id: "Astrakhan Standard Time",
  },
];
const filteredObjects = objects.filter((obj) => {
  const offsetInMinutes = moment.duration(obj.offset).asMinutes();
  return offsetInMinutes > moment().utcOffset();
});

The result is object with id Astrakhan Standard Time

Hope this helps

  • Related