I looked at different entries and I’m confused between new Date() and new DateTimeType(). which should I use? Then I read Rich Koshak’s post on Type conversions and it appeared that I need to multiple conversions to get the current time which is epoch->joda->datetimetype. Why isn’t there a simple function that gets the current date and time. The other examples had to first create a datetime item before creating a rule.
All I want to do is get the current date and time in Rules and insert it in a notification. Can someone help?
rule "Test: current time"
when
Item Virtual_Switch_1 changed
then
val String currentTime = String::format( "%1$tl:%1$tM%1$tp on %1$tA, %1$tB %1$te, %1$tY", new java.util.Date )
logDebug("Rules", "Test: currentTime=[{}]",currentTime)
end
Which logs:
Test: currentTime=[11:00pm on Tuesday, September 19, 2017]
I am far from an expert in this area, but as everybody else I have been bitten by this at more than one time (no pun intended!).
I think there are several ways to skin this cat, so to speak.
Here are a few ways that I have used in my rules:
val timeRightNow = now
Test_vDateTime.postUpdate(new DateTimeType())
Both methods returns the current time, but in different format (data types), and they may be more or less suitable depending on what you will use the time for.
The DateTimeType, as you can see, is very handy if you need to set a DateTime item (as in the example above).
If you goal is to format and print the time, e.g. in a log, then both types can be used, but the different conversion involved may be more or less “complicated”.