Formating hours and minutes with leading 0 as separate values

Hi all. I have this rule file sending the values of Hours, Minutes, Day of the Week and Date via MQTT in exactly this fashion to be read by an Arduino somewhere down the line.
The only thing that eludes me is … if the minute or the hour is less than 10 it is missing the leading 0. How can I change the formating of this? I need the hours and minutes as separate values though.

here is the rules I´m using:

import java.util.Date
import java.text.SimpleDateFormat

rule "publish time"
    when
        Item LocalTime_DatumUndZeit changed
    then
		var hour = (now.getHourOfDay).toString
		var minute = (now.getMinuteOfHour).toString
		var tag = (now.getDayOfWeek).toString
		var SimpleDateFormat df = new SimpleDateFormat( "DD|MM|YY" )
		var String NewDate = df.format ( new Date() )
		publish("mosquitto", "date", NewDate)
		publish("mosquitto", "day", tag)
		publish("mosquitto", "timeHour", hour)
		publish("mosquitto", "timeMinute", minute)
	end

Ahaaaa sometimes its nice that while you wait for help from the community you figure out your own mistakes :wink:

This whole post can be deleted!!!

The error was in var String NewHour dfh = dfh.format ( new Date() ). Should have been var String NewHour = dfh.format ( new Date() )

I vote for keeping this post, as others may have exactly the same question, and you have solved it.

Hi,
I am glad to found this topic. After some research - googling a lot :slight_smile: I have this (very simple) solution:

rule "Publish mqtt time to ESP8266 LCD"
when
    Time cron 	"0 * * * * ?"
then
	MqttTime.sendCommand(String::format("%02d:%02d", now.getHourOfDay(), now.getMinuteOfHour()))
end
log output:

08:49:00.017 [INFO ] [smarthome.event.ItemCommandEvent     ] - Item 'MqttTime' received command 08:49
08:49:00.033 [INFO ] [smarthome.event.ItemStateChangedEvent] - MqttTime changed from 08:48 to 08:49

Maybe will be helpful for someone.

2 Likes