How to convert (and format) a DateTime item in a rule

I have a DateTime item:

DateTime Weather_Forecast_Day_1 "[%1$tA]" <clock> (Weather) { weather="locationId=home, forecast=1, type=condition, property=observationTime" }

The idea of this is to tell me what tomorrow is called (i.e. Tuesday).

Now I want to send this date as a string over MQTT, but I’ve no idea how to:

a) convert it to string
b) format it

I’ve tried this:


I’ve also tried this:

WeatherMQTT_1.postUpdate(String::format( "%1$td %1$tb %1$tl:%1$tM %1$tp", Weather_Forecast_Day_1.state))

Basically, neither work. I managed to get the .toString not to error on the console, however it didn’t format correctly, and also it removed everything that I added onto the MQTT message after that (when I used the + operator to add more text).

Any ideas?

Hi Mat

Try something like this:

var String day = Weather_Forecast_Day_1.state.format("%1$tA")

Hopefully that should work, I quickly tested it in my setup with the following:

rule "test"
    Item test_switch changed to ON
    dateTime.postUpdate(new DateTimeType())

rule "test"
    Item dateTime received update
    var String tmp = dateTime.state.format("%1$tA")

With it having passed midnight for us Brits, my version printed out “Tuesday”.

Daniel, thanks - that worked a treat. (I had to double-take, hadn’t realised it was quite so late here!)

Hi, quick follow-up question.

My rule has this:

var String DateTimeStampInitial = String::format( "%1$td %1$tb %1$tl:%1$tM %1$tp", new Date() )

It works, and provides date in this format: 27 Jan 10:17 pm

Can’t remember how I knew how to format it in this way, but can someone tell me where the “reference” for date time formatting is?

e.g. how come the %1$tb formats to give “Jan”?

I’ve looked in the Joda DateTimeFormat manual, but nowhere can I find the b formatting operator!

Hi Mat, try here:

which specifies

'b' Locale-specific abbreviated month name, e.g. "Jan", "Feb".


Thanks so much!

This page has comprehensive solutions : DateTime Conversion (openHAB 3.x)