2

The app I'm working on relies on forecast data from weather.gov API. For each location, there is a different endpoint. The data schema is pretty standard, like this:

https://api.weather.gov/gridpoints/EAX/41,43

All properties (temperature, wind speed, wind direction, etc.) have a list of values, each one for a given period. The period is formatted this way:

2018-04-27T04:00:00+00:00/PT1H

Which, I guess, means 1 hour starting at 4:00 (UTC) on Apr 4th, 2018.

If I want to get the current temperature, I would so something like this:

const now = new Date();
let currentTemperature;
data.properties.temperature.values.forEach((value) => {
    if (now in value.validTime) {
        currentTemperature = value;
    }
});

The now in value.validTime is just a pseudo-condition. I know that won't work the expected way. I just wanted a way to check if now is in that interval.

I found on another question that:

moment does parse ISO-formatted durations out of the box with the moment.duration method.

I think I could break the date given by the API in two parts, this way:

const [ start, duration ] = value.validTime.split('/');

And then parse the duration using moment's function. However, after some research, I couldn't find how to use the duration object directly to perform the check I need.

Actually, I figured out an approach to do that:

const now = moment();
const [ start, duration ] = value.validTime.split('/');
const diff = moment(start).diff(now);
if (moment.duration(duration).asMilliseconds() > diff) {
    // The current time (now) is in this interval.
}

But it seems too much for what looks to have a way simpler solution.

Finally, I'm not necessarily looking for a solution based on moment. I could use a different lib or even plain JS.

Gustavo Straube
  • 3,744
  • 6
  • 39
  • 62

1 Answers1

4

You can simply use isBetween:

Check if a moment is between two other moments, optionally looking at unit scale (minutes, hours, days, etc). The match is exclusive. The first two arguments will be parsed as moments, if not already so.

and add(Duration).

Your code could be like the following:

const now = moment();
const [ start, duration ] = value.validTime.split('/');
const dur = moment.duration(duration);
const end = moment(start).add(dur);
if ( now.isBetween(start, end) ) {
    // The current time (now) is in this interval.
}
VincenzoC
  • 30,117
  • 12
  • 90
  • 112