I'm running into an issue where my app is being accessed from different parts of the world. And, I have a chart to display peak access times. If accessed from a different part of the world (than the origin) I need it to reflect the converted origin time. However, the way it is currently set up, the calculation renders fooPoint.hour
with the value of for example 28
instead of 00:03
(am). I can pinpoint that this occurs in the else
conditional, since, for example, if they would be Accessing from Australia, with a fooPoint.hour = 20
and this.state.timeZoneOffset = -8
. 20 - (-8) = 28
and I would like it to display as 00:04
. I know my calculations are wrong, so can anyone help me format this correctly please?
I failed to mention that fooPoint.hour
is actually a data point I get in the foo
object (which is fetched from an API), so that represents the avg. peak time of certain location. When viewed from another location in a different part of the world, I need to take into account the time zone difference to display in the chart the peak time but on their time zone
Is a library a low technical debt solution?
I have this array of objects as such:
foo: {
hour: 20
}
I obtain the timezone offset as such: let tzOffset = new Date().getTimezoneOffset() / 60;
and store it in state
Then I have:
foo.forEach((fooPoint) => {
fooPoint.hour =
fooPoint.hour - this.state.timeZoneOffset < 0
? fooPoint.hour - this.state.timeZoneOffset + 24
: foorPoint.hour - this.state.timeZoneOffset;
});
So you have two possible conditions that you want to fix:
Try
foo.forEach((fooPoint) => {
fooPoint.hour -= this.state.timeZoneOffset;
fooPoint.hour =
fooPoint.hour < 0
? fooPoint.hour + 24
: foorPoint.hour >= 24
? fooPoint.hour - 24
: fooPoint.hour;
});
Moving the subtraction out is just because I'm lazy and don't want to repeat it five times.
The critical part here is to test for both possibilities.
You might also find it more readable as if
statements.
foo.forEach((fooPoint) => {
fooPoint.hour -= this.state.timeZoneOffset;
if (fooPoint.hour < 0) {
fooPoint.hour += 24;
} else if (fooPoint.hour >= 24) {
fooPoint.hour -= 24;
}
});
The two are functionally the same, but many would find that easier to follow.
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.