简体   繁体   中英

How do I compare two date values from different objects, format them, and test for equality?

I have two arrays containing objects. One looks like this:

const seatGeekEvents = [
      {
        datetime_local: "2020-09-15T20:00:00",
        venue: {
          name: "House of Blues - Boston",
        },
      },
    ]; ...

and the other like this:

 const hourlyForecast = [
      {
        clouds: 40,
        dt: 1600200000, 
        temp: 67.44,
      },
    ]; ...

I would like to make a function that looks through the objects in the arrays, finds out if the time values in the objects are the same, and if they are, returns the data from the objects that have matching times. Later on, I will display the data using HTML.

The eventual goal here is to make an html table of event data with weather data for the time the event starts. The objects are responses returned from fetch.

Here's the function I've come up with to look for matches:

const getDataToDisplay = (seatGeekEvents, hourlyForecast) => {
      const dataToDisplay = [];
      for (i = 0; i < seatGeekEvents.length; i++) {
        const matches = [];
        for (j = 0; j < hourlyForecast.length; j++) {
          if (
            formatEventTime(seatGeekEvents[i].datetime_local) ===
            formatWeatherTime(hourlyForecast[j].dt)
          ) {
            matches.push(seatGeekEvents[i], hourlyForecast[j]);
          }
        }
        return matches;
      }
      return dataToDisplay;
    };

    console.log(getDataToDisplay(seatGeekEvents, hourlyForecast));

The formatting functions I'm using for coverting dt and datetime_local look like this

 const formatEventTime = (startTimeUTC) => {
      const date = new Date(startTimeUTC);
      return date.toLocaleTimeString("en-US", {
        hour: "2-digit",
        minute: "2-digit",
        weekday: "long",
      });
    };

    const formatWeatherTime = (forecastTimeStamp) => {
      const milliseconds = forecastTimeStamp * 1000;
      const dateObject = new Date(milliseconds);
      return dateObject.toLocaleTimeString("en-US", {
        hour: "2-digit",
        minute: "2-digit",
        weekday: "long",
      });
    };

I'd like to understand why my getDataToDisplay() is returning an empty array. Is it just a time formatting issue? Thanks

"1600200000" is probably a time value in seconds since 1970-01-01 which, if it was UTC, resolves to "2020-09-15T20:00:00.000Z".

An offset of -14400 is probably also seconds which resolves to -4:00. So it seems that "1600200000" a local time value for offset -14400, which matches the current offset in New York.

Given a timestamp of "2020-09-15T20:00:00" and offset of -14400, you should parse the string as UTC, then adjust it using the offset to get a Date that can then be compared to other Dates.

Eg

 /** Parse timestamp as UTC and apply provided offset * @param {string} timestamp - ISO 8601 format, no timezone * @param {number} offset - Offset from UTC in seconds * @returns {Date} for timestamp and offset */ function parseISO(timestamp, offset) { // Get values from timestamp let [Y,M,D,H,m,s] = timestamp.split(/\\D/); // Parse as if UTC let date = new Date(Date.UTC(Y, M-1, D, H, m, s)); // Apply offset to adjust to actual UTC date.setUTCSeconds(date.getUTCSeconds() - offset); return date; } let timestamp = '2020-09-15T20:00:00'; let offset = -14400; let date = parseISO(timestamp, offset); console.log('New York: ' + date.toLocaleString('default', {timeZone:'America/New_York'})); console.log('UTC : ' + date.toISOString());

Note that if you want to compare events that are on the same day, you may need to work out how to deal with different time zones and what "same day" means.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM