Read server time in rule using Openhab2

I’d like to have a way to read the local time without using a method that requires an internet connection. Is there a way to read the server time within a rule?

  • Platform information:
    • Openhab2, Dell quad core with 8Gig RAM, Linux Mint 19.3
    • openjdk version “11.0.7” 2020-04-14
      OpenJDK Runtime Environment (build 11.0.7+10-post-Debian-3deb10u1)
      OpenJDK 64-Bit Server VM (build 11.0.7+10-post-Debian-3deb10u1, mixed mode, sharing)

The documentation says you can have time-based triggers in rules. Is that what you need?

Most people use the Joda magic variable now

1 Like

In OH 3.0, now will provide a ZonedDateTime representing the current time and Joda has been removed. You can get this now using…

# Jython
current_time = DateTimeType().zonedDateTime
// rules DSL
val current_time = new DateTimeType.zonedDateTime
1 Like

Got this from another post some where:

Items:

// OH Up Time
//
DateTime	OH_Uptime					"Up Time [%1$tm.%1$td.%1$tY %1$tH:%1$tM]"		<time>				(HomeState)
String		OH_Uptime_HumanReadable		"Readable Up Time [%s]"												(HomeState, Group_HabPanel_Dashboard)

Rules:

rule "OH Readable Up Time"
	when
    	Item OH_Uptime changed or
		Time cron "1 1 * * * ?"
	then
		if (systemStarted.state != ON && OH_Uptime.state != NULL) {
	
			var DateTime dateTime_OH_Uptime = new DateTime((OH_Uptime.state as DateTimeType).zonedDateTime.toInstant.toEpochMilli)
			var diff						= now.millis - dateTime_OH_Uptime.millis
			var String tmp					= null
	
			// http://stackoverflow.com/questions/13018550/time-since-ago-library-for-android-java
			val Number SECOND_MILLIS = 1000;
			val Number MINUTE_MILLIS = 60 * SECOND_MILLIS;
			val Number HOUR_MILLIS   = 60 * MINUTE_MILLIS;
			val Number DAY_MILLIS    = 24 * HOUR_MILLIS;
	
			if (diff < MINUTE_MILLIS) {
				tmp = "just now";
			} else if (diff < 2 * MINUTE_MILLIS) {
				tmp = "a minute";
				} else if (diff < 50 * MINUTE_MILLIS) {
					tmp = String::format("%.2f", diff / MINUTE_MILLIS) + " Minutes";
					} else if (diff < 90 * MINUTE_MILLIS) {
						tmp = "an hour ago";
						} else if (diff < 24 * HOUR_MILLIS) {
							tmp = String::format("%.2f", diff / HOUR_MILLIS) + " Hours";
							} else if (diff < 48 * HOUR_MILLIS) {
								tmp = "since yesterday";
								} else {
									tmp = String::format("%.1f", diff / DAY_MILLIS) + " Days";
								}
	
			OH_Uptime_HumanReadable.postUpdate(tmp)
	
			tmp = NULL
	
			logInfo("OHUpTime", "-----------------------------------------------------------------------------")
			logInfo("OHUpTime", "Human Readable Time is " + OH_Uptime_HumanReadable.state)
			logInfo("OHUpTime", "-----------------------------------------------------------------------------")
		}
end

Best, Jay

I never let children or young goats near my OpenHAB. What did you mean?

Oh my… my phone swapped out Joda for Kids! Corrected!

1 Like