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.
48 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)”
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?
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 😉
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?
Great to hear 🙂 The 1 hour before sunset and 1 hour after sunrise examples are coming in part 3 😉
How exciting! Can’t wait! 😍
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.
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 🙂
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.
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.
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.
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: http://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 🙂
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.
I just did 🙂
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!
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.
@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?
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.
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….!
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.
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?
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.
Awesome blog, thank you. I’ve been having trouble recently with “Get Sunset Time from Weather Conditions” probably since ios15, where I use it to turn on lights after sunset in an automation upon a person arrival:
1- if that above statement is executed on the same day before sunset, it returns today’s sunset time
2- if executed after sunset but before midnight, it returns sunset time for the next day.
3- you can validate the above with 2 statements, get current weather, get sunset time but don’t use formatted dates.
A workaround is to use this blog post and use formatted dates, with one caveat, for regions where they observe DST, the sunset time will be off by one hour on the eve preceding the change. Any clues why HomeKit returns next day sunset time if automation runs after sunset?
If I ask Siri after sunset, it gives today’s sunset time. Thank you!
Hi Aboulfad and thank you for a great question! I must admit I hadn’t even thought about the problem with DST. Thankfully it only happens twice a year, but of course we want a solution with no bugs.
Clearly asking for current weather gives us the time of the next sunset, which in a way makes sense. I’m now doing a test with using “Get Daily forecast at Current Location” instead. It will be sunset in about four hours here, so I’ll get back to you and see if that could be the solution 😉
Ok, it’s now about 10 minutes past sunset where I live and I can confirm that using Get Daily forecast at Current Location in combination with Get Sunset Time from Weather Conditions will fix the problem you highlighted.
When using Get Current Weather I now get the time for tomorrow’s sunset, but using Get Daily forecast gives me the today’s sunset time (which has already passed).
So, this should solve the problem 😉
Wow thank you for the prompt response and the great solution. I never thought Get Daily Forecast would yield different results and didn’t try it. Kudos to you 😄 and much appreciated!
It was a bit of a lucky guess on my part. I’m just happy it worked 😁
I stumbled upon this blog as I navigate through a unique situation hopping there’s a solution out there I haven’t identified.
I installed a Watts hot water recirculating pump which plugs into 110. There’s a timer on the pump but instead I’m using a smart plug so I can control the pump more efficiently. I have geofence set up on Home so when we all leave the pump does not turn on.
I would like the pump to turn run for 5 minutes and off for 15 minutes between the hours of 7am and 11pm. I am using HomeKit Controller and can get the 5 minutes on and 15 minutes off by having 2 automations that each run for 20 minutes but those automations are 24 hours. Is there a way to only run these automations between the house of 7am and 11pm?
Appreciate your help.
This is an interesting problem that can be solved a few different ways. When you say that you configured the automation in HomeKit Controller, I’m guessing you mean the iOS app?
The simplest way of solving this would be to use a second smart plug. The way you configured the smart plug that is connected to the recirculation pump is a great start. However, I would disconnect it from the pump (using it just as a trigger for two other automations) and connect a second smart plug to the pump.
My idea here is that you first make an automation in the Home app using the event An Accessory is Controlled, you select the first smart plug that is automated in the HomeKit Controller app, and then choose Turns On and Time: Specific times, where you select 7am to 11pm. You then go to next, and choose the second smart plug that is connected to the pump and set it to be turned on.
After this you create a second automatin in the Home app using the event An Accessory is Controlled, and again you select the first smart plug that is automated in the HomeKit Controller app, but this time you choose Turns Off. Here, I wouldn’t select any Time, since you don’t want a situation where the pump is on, and never turns off during the night. And if the plug is already off, nothing will happen. Go to next again, and choose the second smart plug connected to the pump, and set it to be turned off.
Does this make sense? If there’s something unclear, just let me know and I’ll try to explain it more clearly. And please let me know if this solved the problem for you 🙂
This is not the only way to solve the problem, but I think it is the easiest.
Thank you for the response.
I’m not sure I completely follow the 2 plugs. I’ve been playing around and am wondering if this works with 1 plug:
Enable Automation Turn on Hot Water Heater (plug) only from 7am to 11pm. Run Scene Hot Water Heater On (turns on the hot water heater every 20 minutes). So in theory between 11pm and 7pm the scene should not run because the plug is off.
Am I thinking this correct?
I really appreciate the help. This is my first semi-complex automation with HomeKit which is why I’m stumped.
I thank you again.
I must admit I haven’t used the app HomeKit Controller, so I’m not sure exactly what is possible to do within it. You can always test with something like a lamp first, if you want to do some tests.
Thank you Stefan. I’ll play around with your first suggestion. I have found HomeKit Controller allows finer tweaking. I appreciate your input.
Hey Stefan – I wanted to circle back and thank you for your help. After taking a step back for a couple of weeks I tackled this automation setting up the way you said. Originally I couldn’t wrap my head around what you were suggesting and how it would work and maybe I still don’t. But thanks to you my automation works as needed. Thank you again! Dan
That’s great to hear! Thanks for taking the time to let me know 🙂
One other question I cannot wrap my head around, would geofence (when last person leaves/arrives) go on the trigger trigger plug or the actual plug the pump is plugged into?
I would think that when the last person leaves you want to turn off the pump directly, so I would use that to turn the plug connected to the pump off. Does anything need to be done when the first person arrives?
Hey Stefan, I a bit of a noob at this but i was hoping you could give me a steer on how i can set my kitchen lights to come on using a motion sensor using all the info above. Ideally, the lights would come on at sunset at 80% for 30min, when motion is detected. At 2230, this would then drop to 20% until sunrise the next day. But only when motion is detected and turn off after 10min
If I can crack this I can do the same with the rest of the house and the Garden. My dream is to never flick a light switch ever again!
And thank you for a really good question. This is actually a much harder problem to solve than it might seem if we want to adhere to the exact rules you stipulated, and if we want to do it all in HomeKit.
Without using Shortcuts, we can either use sunrise to sunset with or without an offset, sunset to sunrise with or without an offset, or time of day, but not a combination of both in the same rule. Solving this without using HomeKit Shortcuts, we would be able to solve the “turn off after 30 minutes” or “turn off after 10 minutes” with ease.
However, when we combine sunset and 22:29 in one automation, and 22:30 and sunrise in the other automation, we are forced to use HomeKit Shortcuts, which makes it quite a bit harder to turn them off after 30 or 10 minutes.
If you were using Homebrige / HOOBS, this would be possible to do with a little bit of work using dummy switches as triggers for turning the lamps off. The only other way I can think of is is a quite convoluted way of using smart plugs as triggers. However, this is far from ideal.
There is another possibility, and that’s using another app on your iPhone or iPad to program this automation. As far as I know, this would be possible to do in an app called Controller for HomeKit. However, I have not actually used the app myself as I try to solve everything in the Home app, but in this case I would suggest taking a look at it. With Controller for HomeKit you should be able to solve this problem with two automations.
Thanks for the great information in the blog and it really helped me a lot. In the meantime, I’m still waiting for the “use offsets for sunset and sunrise” blog if that will come soon. Any updates?
Thank you for the comment and for the friendly nudge 😁 I’ll try to have it up within 24 hours. It has been on the back-burner for too long.
The part 3 is now up
Very useful tips. I can follow nearly all the instructions except that I cannot enter variables into the if is between and . I just cannot find a way to enter the variable name (SunRiseTime or SunSetTime) in the field. Just can find the magic to enter variable there. Please advice. Thanks a lot!!!
oh, some text has been stripped. I cannot enter variables into the “if variable is between number and number” statement.
I got an answer to myself. I can select variable when in IOS. I cannot when using macOS (monterey or big sur).
Yes, you are correct that there seems to be some bugs on macOS. I had high hopes for using macOS for creating these HomeKit Shortcuts, but it’s been so buggy I just do it on the phone or iPad. But there’s been quite a few bugs on iOS as well, and it’s pretty normal that I have to exit and open a shortcut back up to be able to edit some parts of it.
Thanks for the blog and sorry for the basic question but I can’t for the life of me get ‘timenow’ in the script.
I want to have ‘if timenow is greater than sunset time’ but can’t seem to get it.
No worries 🙂 The TimeNow variable is created in part 1.
Amazing! Thanks for such a quick reply. I missed part 1. Much appreciated
No problem! And sorry, it could probably have been a bit more clear in the text 🙂 If there’s anything else you’re wondering about, just drop a comment 😉