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:
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.