HomeKit Automation Tips

Getting more out of your smart home devices

The power of the Format Date function and how to use it for shortcuts using time of day or sunrise/sunset (part 2)

This is part two of the power of the Format Date function, and it will build on what we looked at in part 1. We’ll look at how we can utilize the Format Date function for use with the sunrise and sunset. In part three we’ll look at using this technique with offsets (for example if current time is between sunrise minus 30 minutes and sunset plus one hour).

(In case you’re using an adblocker, please consider whitelisting this site. Any revenue from Google ads goes to the costs of running this site.)


1. Getting the time of sunrise and sunset

To find out at what time sunrise and sunset occurs in your current location, we have to use the Current Weather function. The Current Weather function contains a plethora of data, such as temperature, pressure, UV index, wind speed and direction, and a lot more. Sunrise and sunset time are also part of this list.

As you use Get Details of Weather Conditions after Get current weather at Current Location, you’re able to choose between all of these data points. If we choose sunrise or sunset, we’re actually being returned a date and time value. And it’s important to know that the data isn’t updated exactly at midnight, but perhaps somewhere in the first hour of the new day.

Why is this important? If you keep the sunrise as a time and date value, and you use it in an if-statement where you compare it to Current Date, you can do conditions like is after, is before, is today etc. But if your if-statement says “If Current Date is after Sunrise Date”, and the check is being done just after midnight, the result would be false, because it would compare the sunrise of the day before instead of the new day.

This is why I suggest you use the Format Date function as we did in part 1, and convert the date and time value, extract the time, and convert it into a simple number. If we do this, we can use it exactly as we used the TimeNow variable that we created from Current Date in part 1.

In this example a light is being triggered by a motion sensor, and the following conditions apply:

  • if the time is between 5:00 AM and sunrise, the lights turn on to 50%
  • if the time is between sunrise and sunset, the lights turn on to 100%
  • if the time is between sunset and midnight, the lights turn on to 30%
  • if none of the above are true, the lights will turn on to 10%

I also assume that we’ve already created the variable TimeNow, which is a number containing the current time in military style time (as we did in part 1).

Start by adding Get current Weather at Current Location (a good tip is to actually put in your address here, as it seems to speed up the shortcut a little bit). To get the actual sunrise date, we need to use Get Details of Weather Conditions, and here we choose Sunrise Time as the detail.

We then add the Format Date action. Sunrise Time should be preselected as the Input. Press Show More, Date Format and Custom. In Format String, you replace the default value with the letters Hmm. Remember that these are case sensitive.

At this point we’ll add the Get Numbers from Input action (it often works without this step, but every now and then it doesn’t recognize the numbers as a number value, so I often use this extra step).

Next, we’ll save the number into a variable with the Set Variable action. We’ll use the name SunriseTime.

We then do the same thing for sunset, but we can omit Get current Weather at Current Location, as we are able to tap into the first query. As we add Get Details of Weather Conditions, we choose Sunset time as the detail. We now have to link this to the earlier weather query. As you can see, the Weather Conditions (in Get Sunset Time from Weather Conditions) is semi-transparent. That means it is not connected to a weather query.To do that we click semi-transparent text, choose Select Magic Variable and scroll up to Get current weather at Current Location and select Weather Conditions.

After this, we add the Format Date action, and do the same formatting as we did for the Sunrise date. Press Show More, Date Format and Custom. Next, replace the default string with Hmm.

We add another Get Numbers from Input, and finish this part by creating a new variable with Set Variable, and naming it SunsetTime.

You should now have three variables TimeNow (that we created in part 1), SunriseTime and SunsetTime.

2. Using the numbers in if-statements

Next, we’ll start with the if-statements. One good way to do them would be to use nested if-statements with Otherwise. However, I feel like this could become a bit confusing in this example, so I’ll only do subsequent if-statements instead.

We start by adding the if-statement for the time between 5:00 AM and sunrise, where the lights are turned on to 50% brightness.

The second if-statement is for the time between sunrise and sunset, where the lights are turned on to 100% brightness.

The third if-statement is for the time between sunset and one minute before midnight, where the lights are turned on to 30%.

And the fourth and final if-statement is for the time between midnight and 4:59 AM.


3. Possible problem with this shortcut

Depending on your location and time of year, it might be that this shortcut doesn’t work for you. In southern Finland around midsummer, the sunrise is before 4:00 AM and the sunset is at almost 11:00 PM. However, in northern Finland, there is actually a time in summer when the sun does not set at all for about 60 days. This would of course break the whole shortcut, since the if-statements do not make any sense at that point.

To fix this, we would need to add additional if-statements to if the SunriseTime and SunsetTime have values that work in this shortcut. If you want to see how to do that, let me know in the comment section below.

In part three we’ll see how to use offsets for sunset and sunrise (for example if TimeNow is between sunrise minus 30 minutes and sunset plus one hour).

If you’ve got any questions about what was explained in this post, please leave a comment and I’ll try to explain it more thoroughly.

21 thoughts on “The power of the Format Date function and how to use it for shortcuts using time of day or sunrise/sunset (part 2)”

  1. Hello Stefan! Thanks for the great automation tips. I tried to create the automation, including the sunset and sunrise times based on you description in two different room. In one room, everything is working perfectly, however in the other room, nothing happens. If I run the shortcut in the non-working room, the result is the sunrise time only (Hmm), but the lights are not turning on. I double checked the two shortcut for the two rooms, but there is no difference at all (except the motion sensor and the lights of course). Can you give me any tips, what could cause such a discrepancy?

    1. Hi MR. L!
      The first thing I would check is the line with “Get Sunset Time from Weather Conditions”. Did you remember to connect Weather Conditions to Weather Conditions in “Get current weather at Current Location” with the magic variable? That’s an easy thing to miss. If the “Weather Conditions” part is semi-transparent, it’s not connected.

      If that wasn’t the problem, let me know, and we’ll try to solve it 😉

  2. Your automation tips has been working amazing. I’m also wondering, if I can use the same shortcut format for 1 hour before sunset and 1 hour after sunrise?

    1. Great to hear 🙂 The 1 hour before sunset and 1 hour after sunrise examples are coming in part 3 😉

  3. Stefan
    I have recently discovered your blog and I’m soaking to all up. We went down the Homekit rabbit-hole as part of our foray into automation 4 years ago. Everything we got (including our Apple TV which we initially got only as a home hub) paid for itself within 6 months on our reduced electric bills. I had been looking forward to some scripting abilities with IOS 14. Haven’t had a chance to play with that yet although I have some ideas on what I would like to try. On that note: if you do scripting in Shortcuts, does that reside on your hub too? I ask because I do most of my Shortcuts on my phone and it goes wherever I do.

    1. Hi David,
      As usual, the way Apple names things is a bit confusing. Just as they’ve got AppleTV (the box), AppleTV (the app) and AppleTV+ (the streaming service), they also have Shortcuts the app, personal shortcuts (macros running on your iPhone or iPad) and home shortcuts (macros running on your HomeKit hub).

      Home shortcuts, like the shortcuts on this website, reside on the hub (and perhaps in iCloud as well). At least that’s what I think since the hub is the only thing that need to be in the home for the automations to run.

      If you get stuck with any of your automation/home shortcuts ideas, just let me know, and I’ll try to help 🙂

      1. Stefan;
        Thanks for the prompt reply in answering my question and I will appreciate any help. Everyone in our household share calendars and I would like to use that as a scripting basis for figuring occupancy.
        The lighting script warning that the lights are about to go off looks like it would help with two situations we have.
        We have also have a Homebridge setup on a Raspberry Pi; but that has been primarily to link our alarm system to HomeKit. As it has not entirely been reliable with anything else, even though I have tweeked it countless times, we are sticking to genuine HomeKit devices.
        We have two motion sensors per each high traffic areas where we want the lights to stay on. Although more expensive initially, the overlapping zones of detection, differing areas of detection and the rules that specify either sensor will keep the light(s) on while both sensors have to show no motion as a condition for the lights to shut off; results in very satisfactory performance.
        We have 67 (including the Homebridged ones) devices as part of our HomeKit setup. That includes our garage door, every door and window has a contact sensor, lots of plugs, light bulbs, and dimmers. Knowing I can add more is good although we are mostly “built out” at this point.

        1. I don’t think HomeKit has any way of accessing calendars, at least natively. I’m sure there are ways to get around it by using for instance Homebridge or some other services, but out of the box I does not work.

          We’re allowing HomeKit to have access to our iPhones’ locations, so that way we are able to use the automation triggers like When X arrives or When anyone arrives or even When the first person arrives. And you can of course do the same for leaving the home. I’ve then set up dummy switches in Homebridge (I use HOOBS) for each person, so there is a dummy switch which turns on when I come home and turns off when I leave. You can of course have a single dummy switch for when the first person arrives and the last person leaves. I can then use this dummy switch in shortcuts to check if anyone is home or not. I use a few dummy switches for different “states”, for instance Sleeping.

          I’ve been planning to do a post about using more than one motion sensor for the same area, and how to configure the shortcut to make them work as one system for turning off the lights. That’s probably going to be the next post after part 3 of this one.

  4. Sorry to slightly hijack this, Stefan but I’d really like a way to be able to subscribe to your page so as to get notified of new posts or replies to comments – Is there any way you can add that please as I actually missed your two most recent posts.

    1. Hi Keith,
      I was actually thinking of letting people create subscriber accounts before, but checking the logs, I noticed that there had been a ton of ongoing malicious attempts to log into the site, probably attempts to take it over. So, as an extra step of security, I locked down the login page to be accessible only from my own IP-address.

      However, if you want to be notified by new posts, you can use the RSS feed: https://homekitautomationtips.com/feed/

      And for comments, the RSS feed is:

      You should be able to add these to your email client or a standalone RSS reader. Hope this helps 🙂

      1. Stefan, I wonder if you can email me please, you’ve got my email address as I’ve entered it when posting this.

        I have another question for you but I’m not sure if it’s something you’d be interested in as it’s quite a complicated one and I’m not even sure if it’s possible.


  5. I have an idea for an automation, though I don’t know if it’s possible.
    My goal would be to have one light turn on in a special color if the weather temperature is warm enough, as an alert that I should open my windows. [You could do something similar with a light to indicate a storm warning, etc.]
    The issue is how to create an automation that “listens” to the weather and triggers when a weather detail meets the condition. From my reading about HomeKit and shortcuts, this is not possible.
    Do you know any way to do this?

    Thanks for your blog, I’m subscribing to the RSS feed. I am learning so much from your posts!

    1. You are correct in that there is no way right now to use weather conditions as triggers. But you can of course create automations that run at certain time of day, which in turn run a shortcut that checks for different weather conditions. My solution for this (or rather things close to this) is using a Raspberry Pi with Homebridge (I’m actually using HOOBS, which is a very user-friendly version of Homebridge). This gives me the ability to create virtual switches that run in Homebrigde, but HomeKit sees as normal switches. I can then create an automation that runs a shortcut every time the virtual switch is flipped.

      By using Scheduled virtual switches, I can make it turn on the switch as often I want to, for instance every 15 minutes or every hour. This also means that I only need to write and update a single shortcut for this. If you create 20 automations in HomeKit that run between 10 AM and 8 PM, you’ll need to write the same shortcut 20 times… and then if you want to change something, you’ll need to change it in all 20 shortcuts. For someone who is more used to scripting like yourself, I really like this solution. I can do much more with HomeKit, but I’m still able to keep it simple to use, and I can control everything from the phone or computer.

      As I’ve done some web development, I’m also using a Raspberry Pi at home that runs a local web server 24/7 for different projects, for instance logging from HomeKit.

  6. @Stefan, this is such a great blog! I’ve been tinkering around with homekit automations last night following your posts, having my kitchen Philips Hue lightstrips turn on to full brightness from Sunset -> 2359, and then from midnight to sunrise for it act as a nightlight, using the Philips Hue sensor.

    It’s a shame that Apple don’t have this functionality baked in, seems quite lacking.

    I have been trying to operate another automation, hoping you can help? When the first person walks into the kitchen, (between 0700-0930) I want to play a specific playlist. I have set this up using the baked in automation steps “when motion detected between specific times, trigger music to play on HomePod), however the issue is that each time motion is then subsequently detected (either myself or another person) the playlist starts playing from the beginning again…! Any tips/advice you can provide to stop this from happening?

    1. Hi Sam,
      Thank you 😊 I’m glad you like it.

      About your automation, I don’t have a HomePod, so I’m not sure in case you’re able to use it in an if-statement (to check if the HomePod is playing at the moment). I just checked that I can’t use an AppleTV in an if-statement, so I’m guessing it might be the same with the HomePod.

      However, there is another way around it. What you really want to do is to have a “state variable” to check if it has already started playing that morning (something that you can set to true or false, that can be checked in an if-statement, and that is not contained only within the shortcut). Of course, this is not something built-in into HomeKit, but you can create your own using a smart plug for that (one that isn’t used for anything else). This is actually how I’ve overcome this limitation.

      So, if you would do that, the logic would be like this:

      Using the same automation (between 0700 and 0930, if motion is detected), but converting it into a shortcut.

      You start the shortcut with an if-statement checking if the smart plug is off. If it’s off, you turn it on and start playing the music playlist. If it’s on, you do nothing.

      You then create another automation running at a designated time (perhaps 10:00 AM) that turns the smart plug back off (it resets the variable for the next morning).

      In this case the smart plug is the state variable that let you know in case the music has already been started that morning. It works as a global variable, meaning it is accessible from any shortcut you want, and it is perpetual (meaning it lives outside the shortcut).

      I’m not sure if I’ve explained this well. Just let me know if there’s something unclear.

      1. Thanks for the detailed input Stefan

        Unfortunately I don’t think a smart plug would be the way to go, as I have all my music coming via the HomePod and so turning it off/on each time would disrupt other various automations I have and Siri interactions. No worries though, fingers crossed Apple provide the ability to use this in the next iOS update….!

        1. Sorry, I didn’t explain it in a good way. In my suggestion, the smart plug is not connected to anything but power, it is just sitting there as a “flag” to remember if the music has already started playing that morning. The smart plug is on = the flag is up = music has already played that morning, the smart plug is off = the flag is down = the music has not played that morning.

          So, the shortcut starts by checking whether the flag is raised (the music has already played that morning), else it will raise the flag and start playing music. If the shortcut is run a second or third time that morning, it will see that the flag is already raised, and it will exit the shortcut without doing anything more.

  7. Great tips. I’ve been playing around with this and assume that these new variables are not global and need to be recreated in every shortcut and called as a magic variable. Is that the case?

    1. You are correct. All variables are local to the shortcut they are created in. However, for simple boolean variables (true or false), you can use smart plugs (that are not used for anything else), or if you use something like Homebridge, you can use dummy switches as global boolean variables.

Leave a Comment

Your email address will not be published. Required fields are marked *