Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

using moment js utc offset to filter an array of objects

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading