Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

javascript - Using moment.js to find the index of an object matching today's date

I am trying to find the index of an object in an array that contains a timestamp that matches the current date. Today is the 27th, so based off of my dataset, it should return the first index. I have tried two solutions, neither of which work for different reasons. I am open to using a solution to either method.

I have tried using an exact string match.

const index = _.findIndex(data, function(day) { 
   return day.timestampUtc === moment().startOf('day').toISOString() })

The above does not work because it is trying to match 2021-01-27T00:00:00Z to 2021-01-27T06:00:00.000Z which never catches because it would return undefined.

I have also tried

const index = _.findIndex(data, function(day) { 
   return moment(day.timestampUtc).day() === moment().day() }) //should return 1, but returns 2

This one didn't work because using moment(day.timestampUtc) would evaluate it to the day before due to timezone offset, so my returned index would be one too high because it evaluates against one day early.

data

[{
  timestampUtc: "2021-01-26T00:00:00Z"
  weatherCodeType: "FLURRIES"
 },
 {
  timestampUtc: "2021-01-27T00:00:00Z"
  weatherCodeType: "RAIN"
 }, //I want this one
{
  timestampUtc: "2021-01-28T00:00:00Z"
  weatherCodeType: "SNOW"
 },
]
question from:https://stackoverflow.com/questions/65926686/using-moment-js-to-find-the-index-of-an-object-matching-todays-date

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should set time to 0 and i think it's better to compare the values, not the strings:

index = _.findIndex(data, (day) => {
  var today = moment().utc()
  today.set({ hour: 0, minute: 0, second: 0, millisecond: 0 })
  return moment.utc(day.timestampUtc).valueOf() === today.valueOf()
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...