Skip to content

Commit

Permalink
7th day timezone hotfix (#327)
Browse files Browse the repository at this point in the history
  • Loading branch information
solderq35 authored May 13, 2024
1 parent 95f7ef3 commit 5028f6a
Showing 1 changed file with 35 additions and 12 deletions.
47 changes: 35 additions & 12 deletions backend/dependencies/nodejs/models/pacific_power_recent.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,49 @@ const DB = require('/opt/nodejs/sql-access.js')

class PacificPowerRecent {
async get() {
// Get Unix TimeStamp for 11:59:59 PM GMT of 7 days ago
await DB.connect()
const currentDate = new Date()
const date = new Date(currentDate)
date.setUTCHours(0)
date.setUTCMinutes(0)
date.setUTCSeconds(0)
date.setUTCMilliseconds(0)
const endTimestamp = Math.floor(date.getTime() / 1000) // End of today in seconds

date.setDate(date.getDate() - 7)
const startTimestamp = Math.floor(date.getTime() / 1000) // 7 days ago in seconds
// see automated-jobs/SEC/readSEC.js for original function
// Automatically detects the timezone difference of US Pacific vs GMT-0 (7 or 8 depending on daylight savings)
// https://stackoverflow.com/questions/20712419/get-utc-offset-from-timezone-in-javascript
const getOffset = timeZone => {
const timeZoneName = Intl.DateTimeFormat('ia', {
timeZoneName: 'shortOffset',
timeZone
})
.formatToParts()
.find(i => i.type === 'timeZoneName').value
const offset = timeZoneName.slice(3)
if (!offset) return 0

const matchData = offset.match(/([+-])(\d+)(?::(\d+))?/)
if (!matchData) throw `cannot parse timezone name: ${timeZoneName}`

const [, sign, hour, minute] = matchData
let result = parseInt(hour) * 60
if (sign === '+') result *= -1
if (minute) result += parseInt(minute)

return result
}

// Get Unix TimeStamp for 11:59:59 PM GMT of 7 days ago
const dateObjUnix = new Date(
// (days * hours * minutes * seconds * ms)
new Date().getTime() - (7 * 24 * 60 * 60 * 1000 + getOffset('US/Pacific') * 60 * 1000)
)

dateObjUnix.setUTCHours(23, 59, 59, 0)

const timestamp7DaysAgo = Math.floor(dateObjUnix.getTime() / 1000) // Convert milliseconds to seconds

return DB.query(
`SELECT MAX(time) as time, MAX(time_seconds) as time_seconds, pacific_power_meter_id
FROM pacific_power_data
WHERE time_seconds >= ? AND time_seconds <= ?
WHERE time_seconds >= ?
GROUP BY pacific_power_meter_id, DATE(FROM_UNIXTIME(time_seconds))
ORDER BY pacific_power_meter_id, time_seconds ASC;`,
[startTimestamp, endTimestamp]
[timestamp7DaysAgo]
)
}
}
Expand Down

0 comments on commit 5028f6a

Please sign in to comment.