127.0.0.1:8000 smart-home-server / master server / utils / time.js
master

Tree @master (Download .tar.gz)

time.js @masterraw · history · blame

const moment = require('moment-timezone');
const suntimes = require('sunrise-sunset-js');

const one_day = 86400000; // 1000 * 60 * 60 * 24
const one_hour = 3600000; // 1000 * 60 * 60

const weekdays = {
    sunday: 0,
    monday: 1,
    teusday: 2,
    wednesday: 3,
    thursday: 4,
    friday: 5,
    saturday: 6
};

function local_time(time) {
    return moment(time).tz("America/New_York");
}

function toString(time) {
    return (time || local_time()).format("dddd MMM Do hh:mm:ss:SSSS a z");
}

function toShortString(time) {
    return (time || local_time()).format("hh:mm:ss a z");
}

function sunrise(coords) {
    return local_time(suntimes.getSunrise(
        coords.lat, coords.long,
        // Gives sunrise of current day
        new Date(local_time().valueOf())
    ));
}

function sunset(coords) {
    return local_time(suntimes.getSunset(
        coords.lat, coords.long,
        // Gives sunset of previous day so add
        // 1 day to get sunset of current day
        new Date(local_time().valueOf() + one_day)
    ));
}

function trigger_at_time(target_time, callback) {
    let time_remaining = target_time.diff(local_time());
    if (time_remaining < 0) {
        time_remaining += one_day;
    }

    console.log("Event scheduled for", toShortString(target_time));

    return setTimeout(function() {
        console.log("Scheduled event triggered at", toShortString());
        callback();
    }, time_remaining);
}

module.exports = {
    toString: toString,
    toShortString: toShortString,
    now: local_time,
    daytime: function(coords) {
        return local_time().isBetween(
            sunrise(coords),
            sunset(coords)
        );
    },
    sunrise: sunrise,
    sunset: sunset,
    weekdays: weekdays,
    one_day: one_day,
    one_hour: one_hour,
    trigger_at_time: trigger_at_time
};