How do I get the current date and time to use in Rules?

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?

Here is an example:

rule "Test: current time"
    Item Virtual_Switch_1 changed
    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)

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”.


Finally! Thanks Scott. The formatting commands are cryptic but I’m getting used to them.

Thanks Kjetil. I tested it and it works but can it be formatted?

DateTime Sun_Eclipse_Total   "Solar (Total Eclipse) [%1$tA, %1$tB %1$te, %1$tY at %1$tl:%1$tM%1$tp]"	<calendar>	(gAstronomy)   {channel="astro:sun:local:eclipse#total"}


Actually, here is an example where I set the value of a DateTime item and format it for display in a sitemap:


DateTime	Fermenter_LastUpdate	"Last update [%1$tA, %1$tm/%1$td/%1$tY at %1$tl:%1$tM%1$tp]"	<calendar>  (gFermenter)


Fermenter_LastUpdate.sendCommand(new DateTimeType)