typescript 使用moment js utc offset来过滤对象数组

wpx232ag  于 2023-01-27  发布在  TypeScript
关注(0)|答案(1)|浏览(85)

我有一个时区数组,如下所示

{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'}

所以我尝试过滤上面的列表,以找到匹配的utc偏移量,如下所给予

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

所以240分钟是时区数组的“04:00:00”偏移量,所以我的预期输出应该是

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

但它只是返回一个空数组,因为它找不到它。我做错了什么?

nle07wnf

nle07wnf1#

你可以这样做:

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();
});

结果是ID为Astrakhan Standard Time的对象
希望这能帮上忙

相关问题