Doug's Blog

IFTTT Pro After Dark

I wanted a light to turn on only after sunset, and before sunrise, so here’s how I set that up.

IFTTT doesn’t have good tools for showing you what’s going on in the code so this took some trial and error, and a decade’s worth of JavaScript knowledge, but this solution should be copy/paste for most people.

Step 1, Create a New Applet

IFTTT Create Applet Screenshot

Step 2, Add your trigger

For me this was our MyQ integration with our garage door, but this should work with any standard IFTTT trigger

IFTTT Screenshot showing MyQ Door trigger

Step 3, Add a query

I selected Weather Underground, and then Current Weather, which has outputs for sunset and sunrise times for whatever location you give it.

IFTTT Screenshot demonstrating the Current Weather choice

Step 4, Add your action

I wanted to turn on a light plugged into a Wyze outlet, but again, any IFTTT action should work fine here

Step 5, Add your filter

Screenshot of IFTTT process showing Add Filter button

This is where things get fun 🙂 Clicking the “Add Filter” button will open up an editor with a list of variables that are available to you in this filter, as well as actions based on what you’ve selected for your action. In my use case, there’s only one action, to skip the action. Other actions like the Email action will let you use JavaScript to re-compose the Title and Body.

The following code will take the Weather Underground variables and turn them into JavaScript date objects, which we can then compare to the current Date.

Github gist with code, follow link for full code

On line one, we instantiate a new date object with the current date time. You might be able to use the meta data from the action but I found this harder to parse, and it should only differ by a few seconds if your code is running as quickly as IFTTT says it should.

Line two we parse the sunrise time from WU into another date object, and the same with the sunset on line three.

Then we just logically test if the current time is greater than sunrise, and less than sunset. That means it’s daylight out there, so on line 6, we skip our action.

Just save your applet, and it should now only trigger after dark.

Wrapping up

You can see if things are working as expected by opening your applet settings and clicking “View Activity.” IFTTT will report the applet was skipped, and note that it was due to your trigger

IFTTT Screenshot showing applet skipped example

Applets are hard to edit after the fact currently, but filters can be edited easily from the settings screen. One way to test if your filter is working, is to set the Date object to a time that we know is after dark, just add

openTime.setHours(23)

between lines 1 and 2 (or whatever number would make sense if say you’re in Alaska at the height of summer 😉 ) this will override the current date time to whatever hour of the day you set, letting you know if your logic works as expected.

October 7, 2020